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
// Copyright 2024 Lars Wilhelmsen <sral-backwards@sral.org>. All rights reserved.
// Use of this source code is governed by the MIT or Apache-2.0 license that can be found in the LICENSE-MIT or LICENSE-APACHE files.

use std::collections::HashSet;
use crate::lexer::{Lexer, Token};
use crate::ParserError::LexerError;

/// `ParserError` is returned when the parser encounters an error.
#[derive(Debug)]
pub enum ParserError {
    /// The scope (top-level or set of parentheses) is empty.
    EmptyScope,
    /// The scope is missing an operator ('&' or '|').
    MissingOperator,
    /// The parser encountered an unexpected token.
    UnexpectedToken(Token),
    /// The parser encountered a mix of operators ('&' and '|').
    MixingOperators,
    LexerError(crate::lexer::LexerError),
}

impl std::fmt::Display for ParserError {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        match self {
            ParserError::EmptyScope => write!(f, "Empty scope"),
            ParserError::MissingOperator => write!(f, "Missing operator"),
            ParserError::UnexpectedToken(token) => write!(f, "Unexpected token: {}", token),
            ParserError::MixingOperators => write!(f, "Mixing operators"),
            ParserError::LexerError(e) => write!(f, "{}", e),
        }
    }
}

#[derive(Debug, PartialEq, Clone)]
pub enum AuthorizationExpression {
    And(Vec<AuthorizationExpression>),
    Or(Vec<AuthorizationExpression>),
    AccessToken(String),
}

impl AuthorizationExpression {
    pub fn evaluate(&self, authorizations: &HashSet<String>) -> bool {
        match self {
            AuthorizationExpression::And(nodes) => {
                nodes.iter().all(|node| node.evaluate(authorizations))
            }
            AuthorizationExpression::Or(nodes) => {
                nodes.iter().any(|node| node.evaluate(authorizations))
            }
            AuthorizationExpression::AccessToken(token) => authorizations.contains(token),
        }
    }

    pub fn to_json_str(&self) -> String {
        match self {
            AuthorizationExpression::And(nodes) => {
                let mut json = String::from("{\"and\": [");
                for node in nodes {
                    json.push_str(&node.to_json_str());
                    json.push(',');
                }
                json.pop();
                json.push(']');
                json.push('}');
                json
            }
            AuthorizationExpression::Or(nodes) => {
                let mut json = String::from("{\"or\": [");
                for node in nodes {
                    json.push_str(&node.to_json_str());
                    json.push(',');
                }
                json.pop();
                json.push(']');
                json.push('}');
                json
            }
            AuthorizationExpression::AccessToken(token) => format!("\"{}\"", token),
        }
    }
}

#[derive(Debug)]
struct Scope {
    tokens: Vec<AuthorizationExpression>,
    labels: Vec<String>,
    current_operator: Option<Token>,
}

impl Scope {
    fn new() -> Self {
        Scope {
            tokens: Vec::new(),
            labels: Vec::new(),
            current_operator: None,
        }
    }

    fn add_node(&mut self, token: AuthorizationExpression) {
        self.tokens.push(token);
    }

    fn add_label(&mut self, label: String) {
        self.labels.push(label);
    }

    fn set_operator(&mut self, operator: &Token) -> Result<(), ParserError> {
        match operator {
            Token::And => {
                if let Some(Token::Or) = self.current_operator {
                    return Err(ParserError::MixingOperators);
                }
            }
            Token::Or => {
                if let Some(Token::And) = self.current_operator {
                    return Err(ParserError::MixingOperators);
                }
            }
            _ => return Err(ParserError::UnexpectedToken(operator.clone())),
        }
        self.current_operator = Some(operator.clone());
        Ok(())
    }

    fn build(&mut self) -> Result<AuthorizationExpression, ParserError> {
        if self.labels.is_empty() {
            return Err(ParserError::EmptyScope);
        }
        if self.labels.len() == 1 {
            return Ok(AuthorizationExpression::AccessToken(
                self.labels.pop().unwrap(),
            ));
        }
        if self.current_operator.is_none() {
            return Err(ParserError::MissingOperator);
        }
        let operator = self.current_operator.take().unwrap();
        let mut nodes = Vec::with_capacity(self.labels.len() + self.tokens.len());

        while let Some(label) = self.labels.pop() {
            nodes.push(AuthorizationExpression::AccessToken(label));
        }

        while let Some(token) = self.tokens.pop() {
            nodes.push(token);
        }
        match operator {
            Token::And => Ok(AuthorizationExpression::And(nodes)),
            Token::Or => Ok(AuthorizationExpression::Or(nodes)),
            _ => Err(ParserError::UnexpectedToken(operator)),
        }
    }
}

/// `Parser` is used to parse an expression and return an `AuthorizationExpression`-based tree.
pub struct Parser<'a> {
    lexer: Lexer<'a>,
}

impl<'a> Parser<'a> {
    /// Creates a new `Parser` instance.
    ///
    /// # Arguments
    ///
    /// * `lexer` - The `Lexer` instance to use for tokenization.
    pub fn new(lexer: Lexer<'a>) -> Self {
        Parser { lexer }
    }

    /// Parse the input string and return an AuthorizationExpression.
    /// If the input string is invalid, a ParserError is returned.
    ///
    /// # Example
    /// ```
    ///  use std::collections::HashSet;
    ///  use accumulo_access::{Lexer, Parser};
    ///  let input = "label1 & label5 & (label3 | label8 | \"label 🕺\")";
    ///  let lexer: Lexer<'_> = Lexer::new(input);
    ///  let mut parser = Parser::new(lexer);
    ///  let ast = parser.parse().unwrap();
    ///  let authorized_tokens : &HashSet<String> = &[
    ///    String::from("label1"),
    ///    String::from("label5"),
    ///    String::from("label 🕺"),
    ///  ].iter().cloned().collect();
    ///  assert_eq!(ast.evaluate(&authorized_tokens), true);
    /// ```
    pub fn parse(&mut self) -> Result<AuthorizationExpression, ParserError> {
        let mut scope = Scope::new();
        while let Some(result) = self.lexer.next() {
            match result {
                Ok(token) => {
                    match token {
                        Token::AccessToken(value) => scope.add_label(value),
                        Token::OpenParen => {
                            let node = self.parse()?;
                            scope.add_node(node.clone()); // The clone here is apparently important.
                        }
                        Token::And => scope.set_operator(&Token::And)?,
                        Token::Or => scope.set_operator(&Token::Or)?,
                        Token::CloseParen => return scope.build(),
                    }
                }
                Err(e) => return Err(LexerError(e)),
            }
        }
        scope.build()
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::collections::HashSet;

    #[test]
    fn test_check_authorization() {
        let input = "label1 & label5 & (label3 | label8 | \"label 🕺\")";
        let lexer: Lexer<'_> = Lexer::new(input);
        let mut parser = Parser::new(lexer);
        let ast = parser.parse().unwrap();
        let mut authorized_tokens = HashSet::new();
        authorized_tokens.insert(String::from("label1"));
        authorized_tokens.insert(String::from("label5"));
        authorized_tokens.insert(String::from("label 🕺"));

        assert_eq!(ast.evaluate(&authorized_tokens), true);
    }
}