# Write secure Alice applications

> Understand compiler safety limits, validate input, protect secrets, bound work, and manage foreign-code boundaries.

Canonical: https://alice-lang.org/documentation/advanced/security/

[Documentation index](https://alice-lang.org/documentation/llms.txt) · [Complete book](https://alice-lang.org/llms-full.txt)

## Start with the boundary

Alice checks types, possible nil use, immutable reassignment, and recognized concurrent writes. These checks help prevent programming errors. They do not authorize a user, validate a business operation, or sandbox a program.

A local Alice program has the permissions of its host process. A successful compilation does not make untrusted source safe to run. Treat external input and external code as separate trust decisions. The [.NET secure coding guidance](https://learn.microsoft.com/en-us/dotnet/standard/security/secure-coding-guidelines) supplies the platform context.

## Validate before use

Parse external text, verify domain bounds, then perform work. A value with type `Int32` can still be negative, too large, or invalid for a particular operation.

```alice
def quantity(text : String) : Int32
  number = 0
  unless Int32.TryParse(text, out number)
    raise "quantity must be an integer"
  end
  if number < 1 || number > 1000
    raise "quantity must be between 1 and 1000"
  end
  number
end
puts quantity("12")
begin
  puts quantity("5000")
rescue error : Exception
  puts error.Message
end
```

Expected output:

```text
12
quantity must be between 1 and 1000
```

[Edit and run in the Alice playground](https://playground.alice-lang.org/#code=u.ZGVmIHF1YW50aXR5KHRleHQgOiBTdHJpbmcpIDogSW50MzIKICBudW1iZXIgPSAwCiAgdW5sZXNzIEludDMyLlRyeVBhcnNlKHRleHQsIG91dCBudW1iZXIpCiAgICByYWlzZSAicXVhbnRpdHkgbXVzdCBiZSBhbiBpbnRlZ2VyIgogIGVuZAogIGlmIG51bWJlciA8IDEgfHwgbnVtYmVyID4gMTAwMAogICAgcmFpc2UgInF1YW50aXR5IG11c3QgYmUgYmV0d2VlbiAxIGFuZCAxMDAwIgogIGVuZAogIG51bWJlcgplbmQKcHV0cyBxdWFudGl0eSgiMTIiKQpiZWdpbgogIHB1dHMgcXVhbnRpdHkoIjUwMDAiKQpyZXNjdWUgZXJyb3IgOiBFeGNlcHRpb24KICBwdXRzIGVycm9yLk1lc3NhZ2UKZW5k)

The parser distinguishes malformed text from out-of-range quantities. Bound values before multiplying them, allocating buffers, or scheduling jobs. A syntactically valid request can still request more work than the service should perform.

At a web boundary, convert invalid input into a controlled client error, as in the [quote API](https://alice-lang.org/documentation/guides/web.md). Do not expose internal stack traces as public responses.

## Bound time and space

Limit request bodies, uploaded files, collection lengths, recursion, retries, and queued work. Use bounded channels when producers can outrun consumers. Carry cancellation and timeouts through the libraries that support them, then observe completion before releasing resources.

Regexes can consume excessive time on adversarial input. Use suitable patterns, input limits, and the .NET Regex timeout API where needed; a cached regex literal is an allocation convenience, not a timeout policy. See [regex best practices](https://learn.microsoft.com/en-us/dotnet/standard/base-types/best-practices-regex).

## Paths, commands, and queries

External names should not automatically become file paths, shell commands, SQL, type names, or method names. Use a fixed allowed mapping where the domain has a known set of choices. Use parameterized database operations and structured process arguments supplied by the relevant library.

When accepting a path within an allowed root, account for canonicalization, separators, symbolic links, and race conditions in the host filesystem. `Path.Combine` is for composing paths; it is not an authorization check. Prefer generated storage identifiers when users do not need to choose filesystem paths.

## Secrets and cryptography

Keep credentials out of source, URL query strings, public exception text, and diagnostic logs. Environment configuration can avoid committing a secret, but the process and privileged tools can still read it. Use the host's secret-management facility for deployed applications.

Ordinary `rand`/`Random` values are for simulation and sampling. Use established .NET cryptographic APIs for security-sensitive randomness and established libraries for encryption, signatures, and password storage. Algorithms and platform support have specific requirements; consult [.NET cryptography support](https://learn.microsoft.com/en-us/dotnet/standard/security/cross-platform-cryptography).

Pooled buffers can contain old data. Initialize what you read, expose only the valid region, and honor the [pool lease contract](https://alice-lang.org/documentation/advanced/buffers.md). Avoid placing long-lived copies of sensitive data in immutable strings when the design requires controlled clearing.

## Dynamic and native boundaries

`Any`, reflection, `send`, and `method_missing` can move failures to runtime. Do not pass user-selected method names directly to an unrestricted object. Map allowed operations to known typed methods instead.

P/Invoke declarations must match the native ABI. A wrong pointer, size, lifetime, or signature can corrupt memory outside ordinary managed protections. Managed race checks do not prove an arbitrary native library thread-safe. Keep those boundaries small and verify the platform-specific behavior.

## Dependencies and distribution

Restore trusted package sources, review dependency updates, commit the lock file, and keep runtime/toolchain updates deliberate. A lock pins a version; it does not certify the package's behavior or safety. Verify downloaded release checksums through the documented installation flow.

## Test negative cases

Include malformed text, extreme numeric values, absent fields, oversized inputs, denied access, cancellation, and dependency failure in application tests. Test that logs and responses omit secrets, and that every resource is released on failure. These are application contracts in addition to the language's compiler checks.

## Continue reading

- Previous: [Measure allocation and retained memory](https://alice-lang.org/documentation/advanced/profiling.md)
- Next: [Editor setup](https://alice-lang.org/documentation/tools/editors.md)
