# Larky Syntax Overview

> To try it out today, please contact us at <support@vgs.io>

## Larky overview

Larky, which is a VGS adaptation of [Starlark](https://bazel.build/rules/language) project, lets you manipulate your secure data in an imperative way using the Larky language. Larky operations execute larky code in a secure and isolated environment, using the VGS-provided API to store and retrieve tokens.

### Starlark language

[Starlark](https://bazel.build/rules/language) is a dialect of Python; it's a very small and simple language with highly readable syntax.

Example of syntax

```python
# Define a number
number = 18

# Define a dictionary
people = {
    "Alice": 22,
    "Bob": 40,
    "Charlie": 55,
    "Dave": 14,
}

names = ", ".join(people.keys())  # Alice, Bob, Charlie, Dave

# Define a function
def greet(name):
    """Return a greeting."""
    return "Hello {}!".format(name)

greeting = greet(names)

above30 = [name for name, age in people.items() if age >= 30]
```

Detailed spec can be found [here](https:///github.com/bazelbuild/starlark/blob/master/spec.md)

### VGS Larky API

Currently, Larky operation is supported only in an HTTP proxy.

Below is a sample Larky script to redact the account number and all headers in an HTTP request

```python
load("@stdlib//json", json="json") # import json library
load("@stdlib//builtins", builtins="builtins")
load("@vgs//vault", "vault")

def process(input, ctx):
    body = json.loads(input.body.decode("utf-8"))

    # store body in a vault and replace it with an alias
    body['account_number'] = vault.redact(body['account_number'])
    redacted_body = builtins.bytes(json.dumps(body))

    redacted_headers = {}
    for k in input.headers:
        redacted_headers[k] = vault.redact(input.headers[k])

    # construct a redacted response
    input.body = redacted_body
    input.headers = redacted_headers
    return input
```

Your script can contain an arbitrary number of functions, but it must include the `process` function with the following signature; this is an entry point for your script.

```python
def process(input, ctx):
    ...
```

Where `input` is an HTTP [request](https://github.com/verygoodsecurity/starlarky/blob/master/larky/src/main/resources/vgs/http/request.star)/[response](https://github.com/verygoodsecurity/starlarky/blob/master/larky/src/main/resources/vgs/http/response.star) object and `ctx` is a dictionary object to carry additional information between operations.

Depending on the phase (request or response) of the HTTP message, the `input` object type will change.

```python
# On Request
def process(input:VGSHttpRequest, ctx:dict[str,str]):
    ...

# On Response
def process(input:VGSHttpResponse, ctx:dict[str,str]):
    ...
```

#### VGSHttpRequest/VGSHttpResponse interface

| Method/Field                            | Description                                       |
| --------------------------------------- | ------------------------------------------------- |
| `input.body -> bytes`                   | Retrieves HTTP message body in bytes              |
| `input.body = redacted_body`            | Updates HTTP message body                         |
| `input.headers -> Dict<String, String>` | Retrieves a copy of HTTP message headers.         |
| `input.headers = redacted_headers`      | Sets headers with the specified names and values. |
| `input.path -> str`                     | Retrieves HTTP message URI                        |
| `input.path = new_path`                 | Sets HTTP message URI                             |
| `input.query_string -> str`             | Retrieves HTTP URI query string                   |
| `input.query_string = new_query`        | Sets HTTP URI query string                        |
| `input.status_code -> int`              | Retrieves HTTP message status code                |
| `input.status_code = new_status`        | Sets HTTP message status code                     |

#### Vault module interface

The [Vault module](/vault/developer-tools/larky/library-api/vault.md) can be imported and used as an API to redact/reveal data stored in VGS's secure storage.

| Method                                                          | Description                          |
| --------------------------------------------------------------- | ------------------------------------ |
| `vgs.redact(value: str or [str,str...]) -> str or [str,str...]` | Redacts value(s), returns alias(es)  |
| `vgs.reveal(alias: str or [str,str...]) -> str or [str,str...]` | Reveals alias(es), returns value(s)  |
| `vgs.delete(alias: str or [str,str...]) -> str or [str,str...]` | Reveals alias(es), returns alias(es) |

### How to use Larky operation

Send a request to [VGS Support](mailto:support@vgs.io) to enable the Larky feature flag.

Open the Routes page. Find the filter you want to modify and add the Larky operation to the Larky editor or select the operation from the dropdown list. &#x20;

<figure><img src="/files/rtgmc3xXsCY4VgENUpZr" alt=""><figcaption></figcaption></figure>

<figure><img src="/files/k1CFRReDlO7BbP4DE13X" alt=""><figcaption></figcaption></figure>

1. Another way is to export your route using the [dashboard](/vault/developer-tools/vault-management/yaml.md#export-a-single-route) or the [CLI](/vault/developer-tools/vgs-cli.md).
2. Open the downloaded YAML file in your favourite text editor.
3. Find the filter you want to modify and add the larky operation under `operations` section

   ```yaml
   operations:
     - name: github.com/verygoodsecurity/common/compute/larky/http/Process
       parameters:
         script: |
           def process(input, ctx):
             # insert your larky script from step 2 here
             return input
   ```
4. Save the YAML file and [import it via the dashboard](/vault/developer-tools/vault-management/yaml.md#import-multiple-routes) or use the [VGS CLI to programmatically apply the change](/vault/developer-tools/vgs-cli/commands.md#apply).
5. Now make an HTTP request to verify your script.

### Troubleshooting

In case you received an error, you can see what happened via [VGS CLI operations logs](/vault/developer-tools/vgs-cli/commands.md#operations) `vgs logs operations -V <vault_id> -R <request_id> -o json | jq`

### Ready-to-use code samples

You can find working Larky code snippets in [this section](/vault/developer-tools/larky/code-examples.md). We are in the process of adding more examples and are willing to provide all possible variations based on real use cases that we face.


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs.verygoodsecurity.com/vault/developer-tools/larky/larky_overview.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
