### Installation Source: https://github.com/loft-sh/jspolicy/blob/main/vendor/github.com/imdario/mergo/README.md Instructions on how to install the Mergo library using go get. ```APIDOC go get github.com/imdario/mergo ``` -------------------------------- ### Install Mergo Source: https://github.com/loft-sh/jspolicy/blob/main/vendor/github.com/imdario/mergo/README.md Use 'go get' to install the Mergo library. Import it in your Go code. ```go go get github.com/imdario/mergo // use in your .go code import ( "github.com/imdario/mergo" ) ``` -------------------------------- ### Install mapstructure Go Library Source: https://github.com/loft-sh/jspolicy/blob/main/vendor/github.com/mitchellh/mapstructure/README.md Use standard go get to install the mapstructure library. ```bash $ go get github.com/mitchellh/mapstructure ``` -------------------------------- ### Start Local Development Server Source: https://github.com/loft-sh/jspolicy/blob/main/docs/README.md Starts a local development server that reflects changes live without requiring a restart. Assumes dependencies are installed. ```bash $ yarn start ``` -------------------------------- ### Start Development with DevSpace Source: https://github.com/loft-sh/jspolicy/blob/main/CONTRIBUTING.md Use this command to set up the development environment and start the JsPolicy development server. Ensure you have DevSpace, kubectl, and Helm installed. ```bash devspace run dev ``` -------------------------------- ### Install json-iterator/go Source: https://github.com/loft-sh/jspolicy/blob/main/vendor/github.com/json-iterator/go/README.md Use go get to install the json-iterator/go package. ```go go get github.com/json-iterator/go ``` -------------------------------- ### Install go-autorest/autorest/adal Source: https://github.com/loft-sh/jspolicy/blob/main/vendor/github.com/Azure/go-autorest/autorest/adal/README.md Install the Azure Active Directory authentication library for Go. ```bash go get -u github.com/Azure/go-autorest/autorest/adal ``` -------------------------------- ### Initialize Procfs and Get Stats Source: https://github.com/loft-sh/jspolicy/blob/main/vendor/github.com/prometheus/procfs/README.md Initializes the proc filesystem and retrieves CPU statistics. Use this to get started with basic system metrics. ```go fs, err := procfs.NewFS("/proc") stats, err := fs.Stat() ``` -------------------------------- ### Installing go-autorest Packages Source: https://github.com/loft-sh/jspolicy/blob/main/vendor/github.com/Azure/go-autorest/README.md Provides the go get commands to install the core go-autorest packages and its subpackages. ```bash go get github.com/Azure/go-autorest/autorest go get github.com/Azure/go-autorest/autorest/azure go get github.com/Azure/go-autorest/autorest/date go get github.com/Azure/go-autorest/autorest/to ``` -------------------------------- ### Install govalidator Package Source: https://github.com/loft-sh/jspolicy/blob/main/vendor/github.com/asaskevich/govalidator/README.md Use 'go get' to install the govalidator package. You can install the latest version or a specific release using gopkg.in. ```bash go get github.com/asaskevich/govalidator or you can get specified release of the package with `gopkg.in`: go get gopkg.in/asaskevich/govalidator.v10 ``` -------------------------------- ### Install golang.org/x/sys Source: https://github.com/loft-sh/jspolicy/blob/main/vendor/github.com/fsnotify/fsnotify/README.md Ensure you have the latest version of golang.org/x/sys installed, as fsnotify utilizes it instead of the standard library's syscall package. ```console go get -u golang.org/x/sys/... ``` -------------------------------- ### Install urlesc Package Source: https://github.com/loft-sh/jspolicy/blob/main/vendor/github.com/PuerkitoBio/urlesc/README.md Use go get to install the urlesc package. This command fetches and installs the package and its dependencies. ```go go get github.com/PuerkitoBio/urlesc ``` -------------------------------- ### Basic glog Logging Examples Source: https://github.com/loft-sh/jspolicy/blob/main/vendor/k8s.io/klog/v2/README.md Demonstrates basic logging functions like Info, Fatalf, and conditional logging using the V function. These examples show how to log messages at different levels and control verbosity. ```go glog.Info("Prepare to repel boarders") glog.Fatalf("Initialization failed: %s", err) ``` ```go if glog.V(2) { glog.Info("Starting transaction...") } glog.V(2).Infoln("Processed", nItems, "elements") ``` -------------------------------- ### Install Gobuffalo Flect Source: https://github.com/loft-sh/jspolicy/blob/main/vendor/github.com/gobuffalo/flect/README.md Use `go get` to install or update the Gobuffalo Flect package. ```bash go get -u -v github.com/gobuffalo/flect ``` -------------------------------- ### Original Token Parsing Example (v2) Source: https://github.com/loft-sh/jspolicy/blob/main/vendor/github.com/form3tech-oss/jwt-go/MIGRATION_GUIDE.md This is the v2 example for parsing a token, showing direct access to claims via `token.Claims` map. ```go if token, err := jwt.Parse(tokenString, keyLookupFunc); err == nil { fmt.Printf("Token for user %v expires %v", token.Claims["user"], token.Claims["exp"]) } ``` -------------------------------- ### Install Project Dependencies Source: https://github.com/loft-sh/jspolicy/blob/main/docs/README.md Installs project dependencies using Yarn. Run this command in the project root. ```bash $ yarn ``` -------------------------------- ### Install YAML dependency for tests Source: https://github.com/loft-sh/jspolicy/blob/main/vendor/github.com/imdario/mergo/README.md If tests fail due to a missing package, run 'go get' for gopkg.in/yaml.v2. ```bash go get gopkg.in/yaml.v2 ``` -------------------------------- ### Install Stable JSON-Patch Versions Source: https://github.com/loft-sh/jspolicy/blob/main/vendor/github.com/evanphx/json-patch/README.md Install specific stable versions of the json-patch library using these go get commands. ```bash go get -u gopkg.in/evanphx/json-patch.v5 ``` ```bash go get -u gopkg.in/evanphx/json-patch.v4 ``` -------------------------------- ### Import v8go Package Source: https://github.com/loft-sh/jspolicy/blob/main/vendor/rogchap.com/v8go/README.md Import the v8go package to start using its functionalities. ```go import v8 "rogchap.com/v8go" ``` -------------------------------- ### Get App Engine Go SDK Package Source: https://github.com/loft-sh/jspolicy/blob/main/vendor/google.golang.org/appengine/CONTRIBUTING.md Use 'go get -d' to download the App Engine Go SDK package. This command downloads the source code without installing or building it. ```bash go get -d google.golang.org/appengine ``` -------------------------------- ### Using get() to Retrieve Kubernetes Resources Source: https://github.com/loft-sh/jspolicy/blob/main/docs/pages/functions/get.mdx Demonstrates retrieving a Pod, a Namespace with 'smart' caching, and an Ingress with cache disabled. Handles cases where resources might not be found. ```javascript // get() is able to retrieve any resource from the kubernetes cluster either cached or directly // get() takes parameters in the form of (Kind, apiVersion, Name, GetOptions?) // will also work with other CRDs, if the object cannot be found 'undefined' is returned. const pod = get("Pod", "v1", "my-namespace/my-pod"); if (!pod) { print("Pod not found"); } else { print("Pod found"); } // this will try to find the namespace first in the cache (fast) and if not found will // try to find it without cache (slow). Usually trying to get the resource from the cache // is enough, but there might be cases where some requests are faster than cache updates. const namespace = get("Namespace", "v1", request.namespace, {cache: 'smart'}); if (!namespace) { warn("Namespace not found"); } // you can also force cache behaviour by setting the 'cache' option to 'true' or 'false' const ingress = get("Ingress", "networking.k8s.io/v1", "my-namespace/my-config-map", {cache: false}) if (ingress) { print("Found ingress"); } ``` -------------------------------- ### Import gofuzz Library Source: https://github.com/loft-sh/jspolicy/blob/main/vendor/github.com/google/gofuzz/README.md Import the gofuzz library to start using its functionalities. This is the initial step for any gofuzz operation. ```go import "github.com/google/gofuzz" ``` -------------------------------- ### glog Fatal Log Example Source: https://github.com/loft-sh/jspolicy/blob/main/vendor/k8s.io/klog/README.md Shows how to log a fatal error message and terminate the program using glog. ```go glog.Fatalf("Initialization failed: %s", err) ``` -------------------------------- ### Install Development Dependencies Source: https://github.com/loft-sh/jspolicy/blob/main/docs/pages/writing-policies/policy-sdk.mdx Install the necessary development dependencies for the jsPolicy SDK project using npm. ```bash npm install ``` -------------------------------- ### Accessing Kubernetes API with readFileSync() Source: https://github.com/loft-sh/jspolicy/blob/main/docs/pages/functions/readFileSync.mdx This example demonstrates how to read the service account token using readFileSync() and then use fetchSync() to retrieve all namespaces from the Kubernetes API. ```yaml apiVersion: policy.jspolicy.com/v1beta1 kind: JsPolicy metadata: name: "read-file-policy.example.com" spec: operations: ["CREATE"] resources: ["pods"] javascript: | // read service account token. const token = readFileSync("/var/run/secrets/kubernetes.io/serviceaccount/token"); // retrieve all namespaces from the kube service directly, isn't that cool? const res = fetchSync("https://kubernetes.default/api/v1/namespaces", { "method": "GET", "insecure": true, "headers": { "Authorization": "bearer " + token } }) if (res.ok) { const namespaceList = res.json(); namespaceList.items.forEach(namespace => { print(namespace.metadata.name); }); } else { print("Something went wrong (" + res.status + "): " + res.text()); } ``` -------------------------------- ### glog Verbose Logging Example Source: https://github.com/loft-sh/jspolicy/blob/main/vendor/k8s.io/klog/README.md Illustrates how to use verbose logging (V function) to control log output based on a verbosity level. ```go if glog.V(2) { glog.Info("Starting transaction...") } ``` ```go glog.V(2).Infoln("Processed", nItems, "elements") ``` -------------------------------- ### fetchSync() Usage Source: https://github.com/loft-sh/jspolicy/blob/main/docs/pages/functions/fetchSync.mdx Demonstrates how to use fetchSync() to make GET requests and handle potential network errors. ```APIDOC ## fetchSync() ### Description Allows you to make http(s) requests to backend servers synchronously. The syntax is similar to the standard Fetch API, but it does not return a promise. ### Method `fetchSync(url: string, options?: RequestInit): Response` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```javascript // Use fetchSync to make requests to backend servers const res = fetchSync("https://ip.seeip.org/jsonip", { method: "GET", headers: { "X-Custom-HTTP-Header": "test" }, }); if (res.ok) { print("jspolicy ip: " + res.json().ip); } // You can also use try catch to handle network errors try { fetchSync("https://this.will.not.exist.tld"); } catch(err) { print("Catched fetchSync: " + err); } ``` ### Response #### Success Response (200) - **ok** (boolean) - Indicates if the request was successful. - **status** (number) - The HTTP status code of the response. - **statusText** (string) - The status text of the response. - **headers** (object) - An object containing the response headers. - **json()** (function) - Parses the response body as JSON. - **text()** (function) - Parses the response body as text. #### Response Example ```json { "ip": "1.2.3.4", "headers": { "Content-Type": "application/json" }, "status": 200, "ok": true } ``` #### Error Handling Network errors or non-2xx status codes can be caught using a try-catch block. ``` -------------------------------- ### Validating Policy Examples in JavaScript Source: https://github.com/loft-sh/jspolicy/blob/main/docs/pages/why-jspolicy.mdx Demonstrates basic validating policy actions like allowing, denying, or warning requests. Use these for request validation. ```javascript allow() ``` ```javascript deny("This is not allowed") ``` ```javascript warn("We'll let this one slip, but upgrade to the new ingress controller") ``` -------------------------------- ### Using RealClock in Production Source: https://github.com/loft-sh/jspolicy/blob/main/vendor/github.com/jonboulle/clockwork/README.md Shows how to instantiate and use `clockwork.NewRealClock()` for production environments, providing the actual system clock. ```go myFunc(clockwork.NewRealClock()) ``` -------------------------------- ### Basic Structured Logging vs. Standard Library Source: https://github.com/loft-sh/jspolicy/blob/main/vendor/sigs.k8s.io/controller-runtime/TMP-LOGGING.md Illustrates the difference between standard library logging and controller-runtime's structured logging for a common scenario. ```go log.Printf("starting reconciliation for pod %s/%s", podNamespace, podName) ``` ```go logger.Info("starting reconciliation", "pod", req.NamespacedNamed) ``` -------------------------------- ### Basic fsnotify Watcher Usage Source: https://github.com/loft-sh/jspolicy/blob/main/vendor/github.com/fsnotify/fsnotify/README.md This example demonstrates how to create a new watcher, add a file path to monitor, and process file system events and errors in separate goroutines. It logs modified files and any errors encountered. ```go package main import ( "log" "github.com/fsnotify/fsnotify" ) func main() { watcher, err := fsnotify.NewWatcher() if err != nil { log.Fatal(err) } defer watcher.Close() done := make(chan bool) go func() { for { select { case event, ok := <-watcher.Events: if !ok { return } log.Println("event:", event) if event.Op&fsnotify.Write == fsnotify.Write { log.Println("modified file:", event.Name) } case err, ok := <-watcher.Errors: if !ok { return } log.Println("error:", err) } } }() err = watcher.Add("/tmp/foo") if err != nil { log.Fatal(err) } <-done } ``` -------------------------------- ### Install Latest JSON-Patch Source: https://github.com/loft-sh/jspolicy/blob/main/vendor/github.com/evanphx/json-patch/README.md Use this command to get the latest version of the json-patch library for your Go project. ```bash go get -u github.com/evanphx/json-patch/v5 ``` -------------------------------- ### Allow Request and Exit Source: https://github.com/loft-sh/jspolicy/blob/main/docs/pages/functions/allow.mdx This example demonstrates how to use `allow()` to permit requests that do not meet specific criteria, preventing further policy evaluation. It denies pod creation in the default namespace while allowing it elsewhere. ```yaml apiVersion: policy.jspolicy.com/v1beta1 kind: JsPolicy metadata: name: "allow.resource.example" spec: operations: ["CREATE"] resources: ["pods"] javascript: | if (request.namespace !== "default") { allow(); // allow request and exit } deny("Do not create pods in the default namespace"); ``` -------------------------------- ### Cluster Resource Access Functions in JavaScript Source: https://github.com/loft-sh/jspolicy/blob/main/docs/pages/why-jspolicy.mdx Provides examples of built-in functions for interacting with cluster resources. Use these to get, list, create, update, or remove Kubernetes objects. ```javascript get("Pod", "v1", "my-namespace/my-pod") ``` ```javascript list("Namespace", "v1") ``` ```javascript create(limitRange) ``` ```javascript update(mySecret) ``` ```javascript remove(configMap) ``` -------------------------------- ### Using sleep() in a JsPolicy Source: https://github.com/loft-sh/jspolicy/blob/main/docs/pages/functions/sleep.mdx This example demonstrates how to use the sleep() function within a JsPolicy to pause execution for a specified duration. Use this function cautiously in webhooks, as it can affect performance. Consider using {cache: false} with get() and list() for timing-critical webhooks. ```yaml apiVersion: policy.jspolicy.com/v1beta1 kind: JsPolicy metadata: name: "pod-sleep.example.com" spec: operations: ["CREATE"] resources: ["pods"] javascript: | // you should usually never(!) sleep inside a webhook, // however there might be situations where you need to wait for // something to happen in the cluster, so this function exists // // remember you can use {cache: false} as well for get() and list() // if you need timing critical webhooks const before = new Date().getTime(); sleep(1000); // sleep for 1 second print(`Slept for ${(new Date().getTime() - before)}`); ``` -------------------------------- ### Capture and Format Callers Source: https://github.com/loft-sh/jspolicy/blob/main/vendor/github.com/go-stack/stack/README.md Demonstrates capturing a single caller and formatting it in different ways. Also shows how to capture a full trace, trim runtime frames, and print the formatted stack. ```go func DoTheThing() { c := stack.Caller(0) log.Print(c) // "source.go:10" log.Printf("%+v", c) // "pkg/path/source.go:10" log.Printf("%n", c) // "DoTheThing" s := stack.Trace().TrimRuntime() log.Print(s) // "[source.go:15 caller.go:42 main.go:14]" } ``` -------------------------------- ### Convert Format String Logging to Structured Logging Source: https://github.com/loft-sh/jspolicy/blob/main/vendor/github.com/go-logr/logr/README.md Demonstrates how to convert traditional format string logging to structured logging with key-value pairs. Use constant messages and add key-value pairs for format specifiers. ```go logger.Error(err, "client returned an error", "code", responseCode) ``` ```go logger.V(4).Info("got a retry-after response when requesting url", "attempt", retries, "after seconds", seconds, "url", url) ``` ```go logger.Info("unable to reflect over type", "type", fmt.Sprintf("%T")) ``` -------------------------------- ### URL Path Preparation Source: https://github.com/loft-sh/jspolicy/blob/main/vendor/github.com/Azure/go-autorest/README.md Illustrates how multiple WithPath decorators can be used to sequentially build a URL path. This is useful for constructing complex API endpoints by appending path segments. ```go req, err := Prepare(&http.Request{}, WithBaseURL("https://microsoft.com/"), WithPath("a"), WithPath("b"), WithPath("c")) ``` -------------------------------- ### Generate Documentation with Go Source: https://github.com/loft-sh/jspolicy/blob/main/docs/README.md Generates documentation files using a Go script. Ensure you are in the main project directory before running. ```bash cd ../ # main project directory go run -mod=vendor ./hack/gen-docs.go ``` -------------------------------- ### Original ParseFromRequest Example (v2) Source: https://github.com/loft-sh/jspolicy/blob/main/vendor/github.com/form3tech-oss/jwt-go/MIGRATION_GUIDE.md This is the v2 example for parsing a token directly from a request using `jwt.ParseFromRequest`. ```go if token, err := jwt.ParseFromRequest(tokenString, req, keyLookupFunc); err == nil { fmt.Printf("Token for user %v expires %v", token.Claims["user"], token.Claims["exp"]) } ``` -------------------------------- ### Read and Parse Files with procfs Source: https://github.com/loft-sh/jspolicy/blob/main/vendor/github.com/prometheus/procfs/CONTRIBUTING.md Demonstrates reading a file from /proc and preparing it for line-by-line scanning. Use util.ReadFileNoStat to avoid stat calls on continuously changing files. ```go data, err := util.ReadFileNoStat("/proc/cpuinfo") if err != nil { return err } reader := bytes.NewReader(data) scanner := bufio.NewScanner(reader) ``` -------------------------------- ### Install jsPolicy with Helm Source: https://github.com/loft-sh/jspolicy/blob/main/docs/pages/fragments/install.mdx Install jsPolicy to your Kubernetes cluster using Helm v3. This command creates the jspolicy namespace if it does not exist. ```bash helm install jspolicy jspolicy -n jspolicy --create-namespace --repo https://charts.loft.sh ``` -------------------------------- ### Using to.StringPtr for String Pointers Source: https://github.com/loft-sh/jspolicy/blob/main/vendor/github.com/Azure/go-autorest/README.md Shows how to use the `to.StringPtr` helper function from the `to` subpackage to simplify the creation of string pointers for JSON marshaling. ```go s := struct { S *string }{ S: to.StringPtr("foo") } ``` -------------------------------- ### JsPolicy Example with deny() Source: https://github.com/loft-sh/jspolicy/blob/main/docs/pages/functions/deny.mdx This example demonstrates how to use the deny() function within a JsPolicy to block requests based on namespace. It shows denying requests to the 'kube-system' namespace with a simple message, and to the 'default' namespace with a message, reason, and HTTP status code. ```yaml apiVersion: policy.jspolicy.com/v1beta1 kind: JsPolicy metadata: name: "deny.resource.example" spec: operations: ["CREATE"] resources: ["pods"] javascript: | // deny kube-system namespace if (request.namespace === "kube-system") { deny("No new pod allowed in kube-system"); } // deny default namespace with reason and code if (request.namespace === "default") { deny("No new pod allowed in default", "BadRequest", 400); } ``` -------------------------------- ### Retrieve a Kubernetes Resource with `get()` Source: https://context7.com/loft-sh/jspolicy/llms.txt Fetch a single Kubernetes resource using `get()`. It uses the internal cache by default but can be configured with `{ cache: "smart" }` or `{ cache: false }` for live API calls. Returns `undefined` if the resource is not found. ```yaml apiVersion: policy.jspolicy.com/v1beta1 kind: JsPolicy metadata: name: "get.resource.example" spec: operations: ["CREATE"] resources: ["pods"] javascript: | // Default: uses internal cache for low-latency access const pod = get("Pod", "v1", "my-namespace/my-pod"); if (!pod) { print("Pod not found"); } // 'smart' cache: checks cache first, falls back to live API call const namespace = get("Namespace", "v1", request.namespace, { cache: "smart" }); if (!namespace) { deny("Namespace does not exist: " + request.namespace); } // Force a live (non-cached) API server call const ingress = get("Ingress", "networking.k8s.io/v1", request.namespace + "/my-ingress", { cache: false }); if (ingress) { print("Found ingress:", ingress.metadata.name); } // Works with any CRD const myCustomResource = get("MyCustomResource", "mygroup.io/v1", "default/resource-name"); ``` -------------------------------- ### Create a New Trace Source: https://github.com/loft-sh/jspolicy/blob/main/vendor/k8s.io/utils/trace/README.md Use trace.New to create a new trace with optional initial fields. Defer LogIfLong to log the trace if its duration exceeds the specified threshold. ```go func doSomething() { opTrace := trace.New("operation", Field{Key: "fieldKey1", Value: "fieldValue1"}) defer opTrace.LogIfLong(100 * time.Millisecond) // do something } ``` -------------------------------- ### Mutating Policy Example in JavaScript Source: https://github.com/loft-sh/jspolicy/blob/main/docs/pages/why-jspolicy.mdx Shows how to mutate the request payload using `mutate`. This is useful for modifying objects before they are persisted. ```javascript mutate(modifiedObj) ``` -------------------------------- ### Initiate Device Authentication with Context in Go Source: https://github.com/loft-sh/jspolicy/blob/main/vendor/github.com/Azure/go-autorest/CHANGELOG.md Use `adal.InitiateDeviceAuthWithContext()` for initiating device authentication when a context is required. This is a context-aware version of the device authentication initiation. ```go adal.InitiateDeviceAuthWithContext() ``` -------------------------------- ### Basic glog Info Log Source: https://github.com/loft-sh/jspolicy/blob/main/vendor/k8s.io/klog/README.md Demonstrates a basic informational log message using glog. ```go glog.Info("Prepare to repel boarders") ``` -------------------------------- ### Using exit() in a JsPolicy Source: https://github.com/loft-sh/jspolicy/blob/main/docs/pages/functions/exit.mdx This example demonstrates how to use the exit() function within a JsPolicy resource. The code after exit() will not be executed. ```yaml apiVersion: policy.jspolicy.com/v1beta1 kind: JsPolicy metadata: name: "env.example.com" spec: operations: ["CREATE"] resources: ["pods"] javascript: | exit(); // this is never reached deny("I'm not executed"); ``` -------------------------------- ### JsPolicyBundle CRD Example Source: https://github.com/loft-sh/jspolicy/blob/main/docs/pages/reference/policybundle-crd.mdx Defines a JsPolicyBundle resource. The 'bundle' field must contain base64 encoded, gzipped JavaScript code. ```yaml apiVersion: policy.jspolicy.com/v1beta1 kind: JsPolicyBundle metadata: name: "policy-name.company.tld" spec: bundle: "BASE64_ENCODED_GZIP_COMPRESSED_JS_CODE" ``` -------------------------------- ### Initialize Block Device FS and Get Disk Stats Source: https://github.com/loft-sh/jspolicy/blob/main/vendor/github.com/prometheus/procfs/README.md Initializes a filesystem object that requires access to both /proc and /sys, then retrieves block device statistics. Use this for metrics related to disk drives. ```go fs, err := blockdevice.NewFS("/proc", "/sys") stats, err := fs.ProcDiskstats() ``` -------------------------------- ### Get All Helm Release Information Source: https://github.com/loft-sh/jspolicy/blob/main/chart/templates/NOTES.txt Retrieve all details associated with your Helm release. Ensure you use the correct release name and namespace. ```bash helm get all {{ .Release.Name }} -n {{ .Release.Namespace }} ``` -------------------------------- ### Initialize OAuth Configuration Source: https://github.com/loft-sh/jspolicy/blob/main/vendor/github.com/Azure/go-autorest/autorest/adal/README.md Initialize the OAuth configuration with the Azure AD endpoint and tenant ID. ```Go const activeDirectoryEndpoint = "https://login.microsoftonline.com/" tenantID := "TENANT_ID" oauthConfig, err := adal.NewOAuthConfig(activeDirectoryEndpoint, tenantID) applicationID := "APPLICATION_ID" callback := func(token adal.Token) error { // This is called after the token is acquired } // The resource for which the token is acquired resource := "https://management.core.windows.net/" ``` -------------------------------- ### Clone jsPolicy SDK Template Source: https://context7.com/loft-sh/jspolicy/llms.txt Start a new TypeScript policy project by cloning the official jsPolicy SDK template repository. ```bash # 1. Clone the SDK template git clone https://github.com/loft-sh/jspolicy-sdk mypolicies cd mypolicies # 2. Install dev dependencies npm install ``` -------------------------------- ### Create jsPolicy Resource Source: https://github.com/loft-sh/jspolicy/blob/main/docs/pages/quickstart.mdx Define a jsPolicy resource in YAML to enforce custom logic. This example denies resource creation in the 'default' namespace. ```yaml # policy.yaml apiVersion: policy.jspolicy.com/v1beta1 kind: JsPolicy metadata: name: "deny-default-namespace.company.tld" spec: operations: ["CREATE"] resources: ["*"] scope: Namespaced javascript: | if (request.namespace === "default") { deny("Creation of resources within the default namespace is not allowed!"); } ``` -------------------------------- ### CPU Profiling JavaScript Execution in Go Source: https://github.com/loft-sh/jspolicy/blob/main/vendor/rogchap.com/v8go/README.md Shows how to use the v8go CPU profiler to record and analyze the execution time of JavaScript code. It includes starting and stopping the profiler, running scripts, and printing the resulting profile tree. ```go func createProfile() { iso := v8.NewIsolate() ctx := v8.NewContext(iso) cpuProfiler := v8.NewCPUProfiler(iso) cpuProfiler.StartProfiling("my-profile") ctx.RunScript(profileScript, "script.js") # this script is defined in cpuprofiler_test.go val, _ := ctx.Global().Get("start") fn, _ := val.AsFunction() fn.Call(ctx.Global()) cpuProfile := cpuProfiler.StopProfiling("my-profile") printTree("", cpuProfile.GetTopDownRoot()) # helper function to print the profile } func printTree(nest string, node *v8.CPUProfileNode) { fmt.Printf("%s%s %s:%d:%d\n", nest, node.GetFunctionName(), node.GetScriptResourceName(), node.GetLineNumber(), node.GetColumnNumber()) count := node.GetChildrenCount() if count == 0 { return } nest = fmt.Sprintf("%s ", nest) for i := 0; i < count; i++ { printTree(nest, node.GetChild(i)) } } // Output // (root) :0:0 // (program) :0:0 // start script.js:23:15 // foo script.js:15:13 // delay script.js:12:15 // loop script.js:1:14 // bar script.js:13:13 // delay script.js:12:15 // loop script.js:1:14 // baz script.js:14:13 // delay script.js:12:15 // loop script.js:1:14 // (garbage collector) :0:0 ```