Debian Codegraph @

docs/CEL Language Features.md

raw
1 ## CEL Language Features
2
3 [CEL, the Common Expression Language](https://cel.dev/), is a small expression language designed for
4 fast and safe evaluation of user-defined rules. openvpn-auth-oauth2 uses CEL for
5 configuration values that need logic, such as identity validation, deriving the
6 OpenVPN username, and resolving client configuration names. CEL expressions can
7 inspect the variables provided by openvpn-auth-oauth2, call the documented
8 string and list helpers, and return the type required by the specific setting.
9 They cannot access files, make network calls, or execute arbitrary code.
10
11 CEL supports many standard operations:
12
13 ### Comparison Operators
14 - `==` (equals)
15 - `!=` (not equals)
16 - `<`, `<=`, `>`, `>=` (numeric comparisons)
17
18 ### Logical Operators
19 - `&&` (AND)
20 - `||` (OR)
21 - `!` (NOT)
22
23 ### Available context
24
25 The same namespaced context is available to `oauth2.openvpn-username`,
26 `oauth2.validate.expression`, and `openvpn.client-config.expression`:
27
28 | Field | Type | Description |
29 | --- | --- | --- |
30 | `auth.mode` | `string` | `interactive` for the initial login or `non-interactive` for token refresh |
31 | `openvpn.commonName` | `string` | Common name supplied by OpenVPN |
32 | `openvpn.ip` | `string` | OpenVPN client IP address |
33 | `openvpn.sessionState` | `string` | Current OpenVPN session state |
34 | `token.claims` | `map<string, dynamic>` | Raw OAuth2 ID token claims; an empty map when no parsed ID token is available |
35 | `token.ip` | `string` | IP address claim from the OAuth2 ID token; an empty string when unavailable |
36 | `user.subject` | `string` | Provider-independent user subject |
37 | `user.email` | `string` | Provider-independent email address |
38 | `user.username` | `string` | Provider-independent username |
39 | `user.groups` | `list<string>` | Provider-independent list of groups |
40 | `user.roles` | `list<string>` | Provider-independent list of roles |
41
42 `auth`, `openvpn`, `token`, and `user` are typed objects. Use the field names
43 listed above with dot notation. openvpn-auth-oauth2 validates these names and
44 their types when it loads the configuration, so an unknown field prevents
45 startup instead of failing during authentication. Every listed field is
46 present; unavailable strings and lists use empty values.
47
48 `token.claims` remains a `map<string, dynamic>` because OAuth2 providers can
49 return arbitrary claims. Use `has(token.claims.department)` before reading an
50 optional claim.
51
52 Provider data is normalized before CEL runs. For a generic OIDC provider,
53 `user.groups` comes from `oauth2.groups-claim` and `user.roles` comes from the
54 `roles` claim. For GitHub, organizations always populate `user.groups`, and
55 teams always populate `user.roles` in `org:slug` format. Google group validation
56 populates `user.groups` with the configured groups that match the user.
57
58 During `oauth2.openvpn-username`, `user.username` is the provider's username
59 candidate, such as `preferred_username` from an ID token or UserInfo response,
60 or the GitHub login. The expression result becomes the resolved username.
61 `oauth2.validate.expression` and `openvpn.client-config.expression` receive that
62 resolved value in `user.username`. An empty expression or an empty expression
63 result falls back to `openvpn.commonName`.
64
65 Prefer `user.*` for portable expressions. Use `token.claims.*` when a rule
66 depends on a provider-specific raw claim. Raw claims may be absent during a
67 refresh or when identity data comes from UserInfo.
68
69 ### Extension Libraries
70
71 All CEL expressions load the [CEL strings extension](https://pkg.go.dev/cel.dev/cel-go/ext#Strings)
72 and [CEL lists extension](https://pkg.go.dev/cel.dev/cel-go/ext#Lists).
73
74 ### String Functions
75
76 The following string functions are available through the [CEL strings extension](https://pkg.go.dev/cel.dev/cel-go/ext#Strings):
77
78 #### Basic String Operations
79 - `startsWith(<string>)` - Check if string starts with prefix
80 - `endsWith(<string>)` - Check if string ends with suffix
81 - `contains(<string>)` - Check if string contains substring
82 - `matches(<string>)` - Check if string matches a regular expression pattern
83
84 #### Case Conversion
85 - `lowerAscii()` - Convert ASCII characters to lowercase
86 - Example: `'TacoCat'.lowerAscii()` returns `'tacocat'`
87 - `upperAscii()` - Convert ASCII characters to uppercase
88 - Example: `'TacoCat'.upperAscii()` returns `'TACOCAT'`
89
90 #### String Searching
91 - `indexOf(<string>)` - Returns the index of the first occurrence of a substring (or -1 if not found)
92 - Example: `'hello mellow'.indexOf('ello')` returns `1`
93 - `indexOf(<string>, <int>)` - Search starting from a specific position
94 - Example: `'hello mellow'.indexOf('ello', 2)` returns `7`
95 - `lastIndexOf(<string>)` - Returns the index of the last occurrence of a substring
96 - Example: `'hello mellow'.lastIndexOf('ello')` returns `7`
97 - `lastIndexOf(<string>, <int>)` - Search up to a specific position
98
99 #### String Manipulation
100 - `substring(<int>)` - Extract substring from position to end
101 - Example: `'tacocat'.substring(4)` returns `'cat'`
102 - `substring(<int>, <int>)` - Extract substring from start (inclusive) to end (exclusive)
103 - Example: `'tacocat'.substring(0, 4)` returns `'taco'`
104 - `trim()` - Remove leading and trailing whitespace
105 - Example: `' \ttrim\n '.trim()` returns `'trim'`
106 - `replace(<string>, <string>)` - Replace all occurrences of a substring
107 - Example: `'hello hello'.replace('he', 'we')` returns `'wello wello'`
108 - `replace(<string>, <string>, <int>)` - Replace with a limit on number of replacements
109 - Example: `'hello hello'.replace('he', 'we', 1)` returns `'wello hello'`
110 - `reverse()` - Reverse the string
111 - Example: `'gums'.reverse()` returns `'smug'`
112
113 #### String Splitting and Joining
114 - `split(<string>)` - Split string by separator into a list
115 - Example: `'hello hello hello'.split(' ')` returns `['hello', 'hello', 'hello']`
116 - `split(<string>, <int>)` - Split with a limit on number of substrings
117 - Example: `'hello hello hello'.split(' ', 2)` returns `['hello', 'hello hello']`
118 - `join()` - Join list of strings (on a list, not a string)
119 - Example: `['hello', 'mellow'].join()` returns `'hellomellow'`
120 - `join(<string>)` - Join list of strings with separator
121 - Example: `['hello', 'mellow'].join(' ')` returns `'hello mellow'`
122
123 #### String Formatting
124 - `format(<list>)` - Format string with printf-style substitutions
125 - Supports: `%s` (string), `%d` (integer), `%f` (float), `%e` (scientific), `%b` (binary), `%x`/`%X` (hex), `%o` (octal)
126 - Example: `"Hello %s, you have %d messages".format(['Alice', 5])` returns `'Hello Alice, you have 5 messages'`
127
128 #### String Utilities
129 - `strings.quote(<string>)` - Make string safe to print by escaping special characters
130 - Example: `strings.quote('single-quote with "double quote"')` returns `'"single-quote with \"double quote\""'`
131
132 ### List Functions
133 - `in` - Check if an element is in a list
134 - `size()` - Get the size of a list or map
135 - `exists(var, predicate)` - Check if any element matches
136 - Example: `user.groups.exists(g, g == 'vpn-users')`
137 - `all(var, predicate)` - Check if every element matches
138 - Example: `user.groups.all(g, g.startsWith('vpn-'))`
139 - `exists_one(var, predicate)` - Check if exactly one element matches
140 - Example: `user.groups.exists_one(g, g == 'vpn-admin')`
141 - `filter(var, predicate)` - Keep matching elements
142 - Example: `user.groups.filter(g, g.startsWith('vpn-'))`
143 - `map(var, expression)` - Transform elements
144 - Example: `user.groups.map(g, g.lowerAscii())`
145 - `map(var, predicate, expression)` - Transform matching elements
146 - Example: `user.groups.map(g, g.startsWith('vpn-'), g.lowerAscii())`
147
148 The CEL lists extension adds more list helpers:
149
150 - `slice(<int>, <int>)` - Return a sub-list
151 - Example: `['base', 'admin', 'net'].slice(0, 2)` returns `['base', 'admin']`
152 - `flatten()` - Flatten one nested list level
153 - Example: `[['base'], ['admin', 'net']].flatten()` returns `['base', 'admin', 'net']`
154 - `flatten(<int>)` - Flatten a specific number of nested list levels
155 - `sort()` - Sort a list of comparable values
156 - Example: `['net', 'base', 'admin'].sort()` returns `['admin', 'base', 'net']`
157 - `sortBy(var, expression)` - Sort a list by a derived key
158 - Example: `[{'name': 'admin', 'order': 2}, {'name': 'base', 'order': 1}].sortBy(p, p.order).map(p, p.name)`
159 - `reverse()` - Reverse list order
160 - Example: `['base', 'admin'].reverse()` returns `['admin', 'base']`
161 - `distinct()` - Remove duplicate list elements while keeping first occurrence
162 - Example: `['base', 'admin', 'base'].distinct()` returns `['base', 'admin']`
163
164 Example for client configuration:
165
166 ```yaml
167 openvpn:
168 client-config:
169 expression: |
170 (
171 ['base'] +
172 user.groups
173 .filter(g, g.startsWith('vpn-'))
174 .map(g, g.replace('vpn-', ''))
175 .sort() +
176 [user.username]
177 ).distinct()
178 ```
179
180 Example that maps each group to one or more shared config files:
181
182 ```yaml
183 openvpn:
184 client-config:
185 expression: |
186 user.groups
187 .map(g, {
188 'GRP-VPN': ['base-vpn'],
189 'GRP-ADMIN': ['base-vpn', 'admin-routes'],
190 'GRP-NETWORK': ['base-vpn', 'network-routes']
191 }[g])
192 .flatten()
193 .distinct()
194 ```
195
196 ### Map/Object Functions
197 - `has()` - Check if a key exists in a map
198
199 ### Type Conversion
200 - `string()` - Convert value to string (useful for casting claim values)
201
202 For more details, see:
203 - [CEL Specification](https://github.com/google/cel-spec/blob/master/doc/langdef.md)
204 - [CEL Strings Extension](https://github.com/google/cel-spec/blob/master/doc/extensions/strings.md)
205 - [cel-go Strings Documentation](https://pkg.go.dev/cel.dev/cel-go/ext#Strings)
206 - [cel-go Lists Documentation](https://pkg.go.dev/cel.dev/cel-go/ext#Lists)
207
208 ## Error Handling
209
210 ### Missing Claims
211
212 If you try to access a claim that doesn't exist in the ID token without checking first, the validation will fail:
213
214 ```yaml
215 ---
216 # ❌ Bad - will fail if 'department' claim doesn't exist
217 expression: 'token.claims.department == "engineering"'
218 ---
219 # ✅ Good - safely checks for claim existence first
220 expression: 'has(token.claims.department) && token.claims.department == "engineering"'
221 ```
222
223 ### Invalid Expressions
224
225 If a CEL expression has syntax errors, unknown context fields, or incompatible
226 types, openvpn-auth-oauth2 fails to start and logs the compilation error.
227
228 ### Non-Boolean Results
229
230 The expression must evaluate to a boolean. If it evaluates to another type (string, number, etc.), the validation will fail:
231
232 ```yaml
233 # ❌ Bad - evaluates to a string, not a boolean
234 expression: 'openvpn.commonName'
235 ---
236 # ✅ Good - evaluates to a boolean
237 expression: 'openvpn.commonName != ""'
238 ```
239
240 ## Best Practices
241
242 1. **Always use `has()` to check for optional token claims** before accessing them to avoid validation failures
243 2. **Keep expressions simple and readable** - complex logic can be hard to debug
244 3. **Test your CEL expressions** with different token scenarios during development
245 4. **Log validation failures** to help troubleshoot issues
246 5. **Document your validation rules** in comments or documentation for team members.
247
248 ## Security Considerations
249
250 - CEL validation happens **after** OAuth2 authentication, so users must authenticate successfully before CEL rules are applied
251 - CEL expressions cannot access external resources or make network calls - they can only evaluate the provided variables
252 - CEL is sandboxed and safe - expressions cannot execute arbitrary code or affect the system
253 - Combining CEL with other validation options (groups, roles, common name) provides defense-in-depth
254
255 ## Debugging
256
257 If validation fails, check the openvpn-auth-oauth2 logs for error messages. The logs will indicate:
258 - CEL compilation errors (if the expression syntax is invalid)
259 - Evaluation errors (if the expression fails during evaluation)
260 - Which specific validation check failed
261
262 Example log messages:
263 ```
264 failed to evaluate CEL expression: no such key: unknown
265 CEL validation failed
266 CEL expression did not evaluate to a boolean value
267 ```
268
269 ## Performance
270
271 CEL expressions are compiled once at a startup and then evaluated efficiently for each authentication request. The performance impact is minimal, even for complex expressions.