actix-security-core 0.2.3

Spring Security-like authentication and authorization for Actix Web - Core library
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
//! Security expression parser.
//!
//! Parses Spring Security-like expressions into an AST.

use std::fmt;
use std::iter::Peekable;
use std::str::Chars;

use super::ast::{BinaryOp, Expression, UnaryOp};

/// Error type for expression parsing.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ParseError {
    /// Unexpected end of input
    UnexpectedEof,
    /// Unexpected character
    UnexpectedChar(char),
    /// Unexpected token
    UnexpectedToken(String),
    /// Unclosed parenthesis
    UnclosedParen,
    /// Unclosed string
    UnclosedString,
    /// Empty expression
    EmptyExpression,
    /// Invalid function call
    InvalidFunction(String),
}

impl fmt::Display for ParseError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            ParseError::UnexpectedEof => write!(f, "unexpected end of expression"),
            ParseError::UnexpectedChar(c) => write!(f, "unexpected character: '{}'", c),
            ParseError::UnexpectedToken(t) => write!(f, "unexpected token: '{}'", t),
            ParseError::UnclosedParen => write!(f, "unclosed parenthesis"),
            ParseError::UnclosedString => write!(f, "unclosed string literal"),
            ParseError::EmptyExpression => write!(f, "empty expression"),
            ParseError::InvalidFunction(name) => write!(f, "invalid function: '{}'", name),
        }
    }
}

impl std::error::Error for ParseError {}

/// Token types for the lexer.
#[derive(Debug, Clone, PartialEq, Eq)]
enum Token {
    /// Identifier (function name, keyword)
    Ident(String),
    /// String literal
    String(String),
    /// Left parenthesis
    LParen,
    /// Right parenthesis
    RParen,
    /// Comma
    Comma,
    /// AND operator
    And,
    /// OR operator
    Or,
    /// NOT operator
    Not,
    /// Boolean true
    True,
    /// Boolean false
    False,
}

/// A parsed security expression.
///
/// # Example
/// ```ignore
/// use actix_security_core::http::security::expression::SecurityExpression;
///
/// let expr = SecurityExpression::parse("hasRole('ADMIN') OR hasAuthority('write')")?;
/// let result = expr.evaluate(&user);
/// ```
#[derive(Debug, Clone)]
pub struct SecurityExpression {
    /// The original expression string
    source: String,
    /// The parsed AST
    ast: Expression,
}

impl SecurityExpression {
    /// Parses a security expression string.
    ///
    /// # Arguments
    /// * `expr` - The expression string to parse
    ///
    /// # Returns
    /// A parsed `SecurityExpression` or a `ParseError`
    ///
    /// # Example
    /// ```ignore
    /// let expr = SecurityExpression::parse("hasRole('ADMIN')")?;
    /// ```
    pub fn parse(expr: &str) -> Result<Self, ParseError> {
        let tokens = tokenize(expr)?;
        if tokens.is_empty() {
            return Err(ParseError::EmptyExpression);
        }

        let ast = Parser::new(tokens).parse()?;

        Ok(SecurityExpression {
            source: expr.to_string(),
            ast,
        })
    }

    /// Returns the original expression string.
    pub fn source(&self) -> &str {
        &self.source
    }

    /// Returns a reference to the parsed AST.
    pub fn ast(&self) -> &Expression {
        &self.ast
    }

    /// Consumes self and returns the AST.
    pub fn into_ast(self) -> Expression {
        self.ast
    }
}

/// Tokenizes an expression string into tokens.
fn tokenize(expr: &str) -> Result<Vec<Token>, ParseError> {
    let mut tokens = Vec::new();
    let mut chars = expr.chars().peekable();

    while let Some(&c) = chars.peek() {
        match c {
            // Whitespace - skip
            ' ' | '\t' | '\n' | '\r' => {
                chars.next();
            }

            // Parentheses
            '(' => {
                chars.next();
                tokens.push(Token::LParen);
            }
            ')' => {
                chars.next();
                tokens.push(Token::RParen);
            }

            // Comma
            ',' => {
                chars.next();
                tokens.push(Token::Comma);
            }

            // String literals (single or double quotes)
            '\'' | '"' => {
                tokens.push(parse_string(&mut chars)?);
            }

            // Operators
            '&' => {
                chars.next();
                if chars.peek() == Some(&'&') {
                    chars.next();
                    tokens.push(Token::And);
                } else {
                    return Err(ParseError::UnexpectedChar('&'));
                }
            }
            '|' => {
                chars.next();
                if chars.peek() == Some(&'|') {
                    chars.next();
                    tokens.push(Token::Or);
                } else {
                    return Err(ParseError::UnexpectedChar('|'));
                }
            }
            '!' => {
                chars.next();
                tokens.push(Token::Not);
            }

            // Identifiers and keywords
            'a'..='z' | 'A'..='Z' | '_' => {
                tokens.push(parse_identifier(&mut chars));
            }

            // Unknown character
            _ => {
                return Err(ParseError::UnexpectedChar(c));
            }
        }
    }

    Ok(tokens)
}

/// Parses a string literal.
fn parse_string(chars: &mut Peekable<Chars>) -> Result<Token, ParseError> {
    let quote = chars.next().unwrap(); // ' or "
    let mut value = String::new();

    loop {
        match chars.next() {
            Some(c) if c == quote => {
                return Ok(Token::String(value));
            }
            Some('\\') => {
                // Escape sequence
                if let Some(escaped) = chars.next() {
                    value.push(escaped);
                } else {
                    return Err(ParseError::UnclosedString);
                }
            }
            Some(c) => {
                value.push(c);
            }
            None => {
                return Err(ParseError::UnclosedString);
            }
        }
    }
}

/// Parses an identifier or keyword.
fn parse_identifier(chars: &mut Peekable<Chars>) -> Token {
    let mut ident = String::new();

    while let Some(&c) = chars.peek() {
        if c.is_alphanumeric() || c == '_' {
            ident.push(c);
            chars.next();
        } else {
            break;
        }
    }

    // Check for keywords
    match ident.to_lowercase().as_str() {
        "and" => Token::And,
        "or" => Token::Or,
        "not" => Token::Not,
        "true" => Token::True,
        "false" => Token::False,
        _ => Token::Ident(ident),
    }
}

/// Recursive descent parser for security expressions.
struct Parser {
    tokens: Vec<Token>,
    pos: usize,
}

impl Parser {
    fn new(tokens: Vec<Token>) -> Self {
        Parser { tokens, pos: 0 }
    }

    fn parse(&mut self) -> Result<Expression, ParseError> {
        let expr = self.parse_or()?;

        if self.pos < self.tokens.len() {
            return Err(ParseError::UnexpectedToken(format!(
                "{:?}",
                self.tokens[self.pos]
            )));
        }

        Ok(expr)
    }

    fn peek(&self) -> Option<&Token> {
        self.tokens.get(self.pos)
    }

    fn advance(&mut self) -> Option<&Token> {
        let token = self.tokens.get(self.pos);
        self.pos += 1;
        token
    }

    /// Parse OR expressions (lowest precedence)
    fn parse_or(&mut self) -> Result<Expression, ParseError> {
        let mut left = self.parse_and()?;

        while matches!(self.peek(), Some(Token::Or)) {
            self.advance();
            let right = self.parse_and()?;
            left = Expression::Binary {
                left: Box::new(left),
                op: BinaryOp::Or,
                right: Box::new(right),
            };
        }

        Ok(left)
    }

    /// Parse AND expressions (higher precedence than OR)
    fn parse_and(&mut self) -> Result<Expression, ParseError> {
        let mut left = self.parse_unary()?;

        while matches!(self.peek(), Some(Token::And)) {
            self.advance();
            let right = self.parse_unary()?;
            left = Expression::Binary {
                left: Box::new(left),
                op: BinaryOp::And,
                right: Box::new(right),
            };
        }

        Ok(left)
    }

    /// Parse unary expressions (NOT)
    fn parse_unary(&mut self) -> Result<Expression, ParseError> {
        if matches!(self.peek(), Some(Token::Not)) {
            self.advance();
            let expr = self.parse_unary()?;
            return Ok(Expression::Unary {
                op: UnaryOp::Not,
                expr: Box::new(expr),
            });
        }

        self.parse_primary()
    }

    /// Parse primary expressions (functions, booleans, groups)
    fn parse_primary(&mut self) -> Result<Expression, ParseError> {
        match self.peek().cloned() {
            Some(Token::True) => {
                self.advance();
                Ok(Expression::Boolean(true))
            }
            Some(Token::False) => {
                self.advance();
                Ok(Expression::Boolean(false))
            }
            Some(Token::LParen) => {
                self.advance();
                let expr = self.parse_or()?;
                if !matches!(self.peek(), Some(Token::RParen)) {
                    return Err(ParseError::UnclosedParen);
                }
                self.advance();
                Ok(Expression::Group(Box::new(expr)))
            }
            Some(Token::Ident(name)) => {
                self.advance();
                self.parse_function_call(name)
            }
            Some(token) => Err(ParseError::UnexpectedToken(format!("{:?}", token))),
            None => Err(ParseError::UnexpectedEof),
        }
    }

    /// Parse function call arguments
    fn parse_function_call(&mut self, name: String) -> Result<Expression, ParseError> {
        // Expect opening parenthesis
        if !matches!(self.peek(), Some(Token::LParen)) {
            return Err(ParseError::InvalidFunction(name));
        }
        self.advance();

        let mut args = Vec::new();

        // Parse arguments
        if !matches!(self.peek(), Some(Token::RParen)) {
            loop {
                match self.peek().cloned() {
                    Some(Token::String(s)) => {
                        self.advance();
                        args.push(s);
                    }
                    Some(Token::Ident(s)) => {
                        // Allow unquoted identifiers as arguments
                        self.advance();
                        args.push(s);
                    }
                    Some(token) => {
                        return Err(ParseError::UnexpectedToken(format!("{:?}", token)));
                    }
                    None => {
                        return Err(ParseError::UnclosedParen);
                    }
                }

                // Check for comma or closing paren
                match self.peek() {
                    Some(Token::Comma) => {
                        self.advance();
                    }
                    Some(Token::RParen) => break,
                    Some(token) => {
                        return Err(ParseError::UnexpectedToken(format!("{:?}", token)));
                    }
                    None => {
                        return Err(ParseError::UnclosedParen);
                    }
                }
            }
        }

        // Expect closing parenthesis
        if !matches!(self.peek(), Some(Token::RParen)) {
            return Err(ParseError::UnclosedParen);
        }
        self.advance();

        Ok(Expression::Function { name, args })
    }
}