summaryrefslogtreecommitdiff
path: root/src/services/api/rest/models.py
blob: 23ae9be9d9c88c87b79dc0c1555f06722f4b9ebf (plain)
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
# Copyright 2024 VyOS maintainers and contributors <maintainers@vyos.io>
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with this library.  If not, see <http://www.gnu.org/licenses/>.


# pylint: disable=too-few-public-methods

import json
from html import escape
from enum import Enum
from typing import List
from typing import Union
from typing import Dict
from typing import Self

from pydantic import BaseModel
from pydantic import StrictStr
from pydantic import field_validator
from pydantic import model_validator
from fastapi.responses import HTMLResponse


def error(code, msg):
    msg = escape(msg, quote=False)
    resp = {'success': False, 'error': msg, 'data': None}
    resp = json.dumps(resp)
    return HTMLResponse(resp, status_code=code)


def success(data):
    resp = {'success': True, 'data': data, 'error': None}
    resp = json.dumps(resp)
    return HTMLResponse(resp)


# Pydantic models for validation
# Pydantic will cast when possible, so use StrictStr validators added as
# needed for additional constraints
# json_schema_extra adds anotations to OpenAPI to add examples


class ApiModel(BaseModel):
    key: StrictStr


class BasePathModel(BaseModel):
    op: StrictStr
    path: List[StrictStr]

    @field_validator('path')
    @classmethod
    def check_non_empty(cls, path: str) -> str:
        if not len(path) > 0:
            raise ValueError('path must be non-empty')
        return path


class BaseConfigureModel(BasePathModel):
    value: StrictStr = None


class ConfigureModel(ApiModel, BaseConfigureModel):
    class Config:
        json_schema_extra = {
            'example': {
                'key': 'id_key',
                'op': 'set | delete | comment',
                'path': ['config', 'mode', 'path'],
            }
        }


class ConfigureListModel(ApiModel):
    commands: List[BaseConfigureModel]

    class Config:
        json_schema_extra = {
            'example': {
                'key': 'id_key',
                'commands': 'list of commands',
            }
        }


class BaseConfigSectionModel(BasePathModel):
    section: Dict


class ConfigSectionModel(ApiModel, BaseConfigSectionModel):
    pass


class ConfigSectionListModel(ApiModel):
    commands: List[BaseConfigSectionModel]


class BaseConfigSectionTreeModel(BaseModel):
    op: StrictStr
    mask: Dict
    config: Dict


class ConfigSectionTreeModel(ApiModel, BaseConfigSectionTreeModel):
    pass


class RetrieveModel(ApiModel):
    op: StrictStr
    path: List[StrictStr]
    configFormat: StrictStr = None

    class Config:
        json_schema_extra = {
            'example': {
                'key': 'id_key',
                'op': 'returnValue | returnValues | exists | showConfig',
                'path': ['config', 'mode', 'path'],
                'configFormat': 'json (default) | json_ast | raw',
            }
        }


class ConfigFileModel(ApiModel):
    op: StrictStr
    file: StrictStr = None

    class Config:
        json_schema_extra = {
            'example': {
                'key': 'id_key',
                'op': 'save | load',
                'file': 'filename',
            }
        }


class ImageOp(str, Enum):
    add = 'add'
    delete = 'delete'
    show = 'show'
    set_default = 'set_default'


class ImageModel(ApiModel):
    op: ImageOp
    url: StrictStr = None
    name: StrictStr = None

    @model_validator(mode='after')
    def check_data(self) -> Self:
        if self.op == 'add':
            if not self.url:
                raise ValueError('Missing required field "url"')
        elif self.op in ['delete', 'set_default']:
            if not self.name:
                raise ValueError('Missing required field "name"')

        return self

    class Config:
        json_schema_extra = {
            'example': {
                'key': 'id_key',
                'op': 'add | delete | show | set_default',
                'url': 'imagelocation',
                'name': 'imagename',
            }
        }


class ImportPkiModel(ApiModel):
    op: StrictStr
    path: List[StrictStr]
    passphrase: StrictStr = None

    class Config:
        json_schema_extra = {
            'example': {
                'key': 'id_key',
                'op': 'import_pki',
                'path': ['op', 'mode', 'path'],
                'passphrase': 'passphrase',
            }
        }


class ContainerImageModel(ApiModel):
    op: StrictStr
    name: StrictStr = None

    class Config:
        json_schema_extra = {
            'example': {
                'key': 'id_key',
                'op': 'add | delete | show',
                'name': 'imagename',
            }
        }


class GenerateModel(ApiModel):
    op: StrictStr
    path: List[StrictStr]

    class Config:
        json_schema_extra = {
            'example': {
                'key': 'id_key',
                'op': 'generate',
                'path': ['op', 'mode', 'path'],
            }
        }


class ShowModel(ApiModel):
    op: StrictStr
    path: List[StrictStr]

    class Config:
        json_schema_extra = {
            'example': {
                'key': 'id_key',
                'op': 'show',
                'path': ['op', 'mode', 'path'],
            }
        }


class RebootModel(ApiModel):
    op: StrictStr
    path: List[StrictStr]

    class Config:
        json_schema_extra = {
            'example': {
                'key': 'id_key',
                'op': 'reboot',
                'path': ['op', 'mode', 'path'],
            }
        }


class ResetModel(ApiModel):
    op: StrictStr
    path: List[StrictStr]

    class Config:
        json_schema_extra = {
            'example': {
                'key': 'id_key',
                'op': 'reset',
                'path': ['op', 'mode', 'path'],
            }
        }


class PoweroffModel(ApiModel):
    op: StrictStr
    path: List[StrictStr]

    class Config:
        json_schema_extra = {
            'example': {
                'key': 'id_key',
                'op': 'poweroff',
                'path': ['op', 'mode', 'path'],
            }
        }


class Success(BaseModel):
    success: bool
    data: Union[str, bool, Dict]
    error: str


class Error(BaseModel):
    success: bool = False
    data: Union[str, bool, Dict]
    error: str


responses = {
    200: {'model': Success},
    400: {'model': Error},
    422: {'model': Error, 'description': 'Validation Error'},
    500: {'model': Error},
}