├── .github ├── dependabot.yml └── workflows │ ├── ci.yml │ ├── commitlint.yml │ └── upgrade-python-requirements.yml ├── .gitignore ├── .pep8 ├── .pylintrc ├── LICENSE ├── Makefile ├── README.md ├── docs └── decisions │ └── 0001-API-strategy-and-change-management-process.rst ├── openedx.yaml ├── requirements ├── base.in ├── base.txt ├── constraints.txt ├── pip-tools.in ├── pip-tools.txt ├── pip.in ├── pip.txt ├── pip_tools.in ├── pip_tools.txt ├── test.in └── test.txt ├── scripts ├── __init__.py └── aws │ ├── README.md │ ├── __init__.py │ ├── bootstrap.json │ ├── bootstrap.py │ ├── common │ ├── __init__.py │ └── deploy.py │ ├── deploy.py │ ├── flip.py │ ├── monitor.py │ ├── templates │ ├── index.js.j2 │ └── lambda_exec_policy.json.j2 │ └── tests │ ├── fixtures │ └── swagger.json │ ├── test_bootstrap.py │ ├── test_deploy_common.py │ └── test_flip.py ├── swagger ├── api.yaml ├── heartbeat.yaml ├── index.yaml └── oauth.yaml └── tests ├── test_all.yaml ├── test_catalog.yaml ├── test_enterprise.yaml ├── test_enterprise_access.yaml ├── test_heartbeat.yaml ├── test_index.yaml └── test_oauth.yaml /.github/dependabot.yml: -------------------------------------------------------------------------------- 1 | version: 2 2 | updates: 3 | # Adding new check for github-actions 4 | - package-ecosystem: "github-actions" 5 | directory: "/" 6 | schedule: 7 | interval: "weekly" 8 | reviewers: 9 | - "edx/arbi-bom" 10 | -------------------------------------------------------------------------------- /.github/workflows/ci.yml: -------------------------------------------------------------------------------- 1 | name: Python CI 2 | 3 | on: 4 | push: 5 | branches: [ 'master' ] 6 | pull_request: 7 | 8 | jobs: 9 | run_tests: 10 | name: Tests 11 | runs-on: ${{ matrix.os }} 12 | strategy: 13 | matrix: 14 | os: [ubuntu-20.04] 15 | python-version: ['3.11'] 16 | 17 | steps: 18 | 19 | - uses: actions/checkout@v4 20 | - name: Setup Python 21 | uses: actions/setup-python@v5 22 | with: 23 | python-version: ${{ matrix.python-version }} 24 | 25 | - name: Install pip 26 | run: pip install -r requirements/pip.txt 27 | 28 | - name: Install Dependencies 29 | run: | 30 | sudo apt-get update 31 | sudo apt-get install libcurl4-openssl-dev libssl-dev 32 | make requirements 33 | 34 | - name: Run Tests 35 | run: make test 36 | -------------------------------------------------------------------------------- /.github/workflows/commitlint.yml: -------------------------------------------------------------------------------- 1 | # Run commitlint on the commit messages in a pull request. 2 | 3 | name: Lint Commit Messages 4 | 5 | on: 6 | - pull_request 7 | 8 | jobs: 9 | commitlint: 10 | uses: openedx/.github/.github/workflows/commitlint.yml@master 11 | -------------------------------------------------------------------------------- /.github/workflows/upgrade-python-requirements.yml: -------------------------------------------------------------------------------- 1 | name: Upgrade Requirements 2 | 3 | on: 4 | schedule: 5 | # will start the job at 03:00 UTC on Wednesday 6 | - cron: "0 3 * * 3" 7 | workflow_dispatch: 8 | inputs: 9 | branch: 10 | description: "Target branch to create requirements PR against" 11 | required: true 12 | default: 'master' 13 | 14 | jobs: 15 | upgrade_requirements: 16 | runs-on: ubuntu-20.04 17 | 18 | strategy: 19 | matrix: 20 | python-version: ["3.11"] 21 | 22 | steps: 23 | - name: setup target branch 24 | run: echo "target_branch=$(if ['${{ github.event.inputs.branch }}' = '']; then echo 'master'; else echo '${{ github.event.inputs.branch }}'; fi)" >> $GITHUB_ENV 25 | 26 | - uses: actions/checkout@v4 27 | with: 28 | ref: ${{ env.target_branch }} 29 | 30 | - name: setup python 31 | uses: actions/setup-python@v5 32 | with: 33 | python-version: ${{ matrix.python-version }} 34 | 35 | - name: install dependencies 36 | run: sudo apt-get install libcurl4-openssl-dev libssl-dev 37 | 38 | - name: make upgrade 39 | run: | 40 | cd $GITHUB_WORKSPACE 41 | make upgrade 42 | 43 | - name: setup testeng-ci 44 | run: | 45 | git clone https://github.com/edx/testeng-ci.git 46 | cd $GITHUB_WORKSPACE/testeng-ci 47 | pip install -r requirements/base.txt 48 | - name: create pull request 49 | env: 50 | GITHUB_TOKEN: ${{ secrets.REQUIREMENTS_BOT_GITHUB_TOKEN }} 51 | GITHUB_USER_EMAIL: ${{ secrets.REQUIREMENTS_BOT_GITHUB_EMAIL }} 52 | run: | 53 | cd $GITHUB_WORKSPACE/testeng-ci 54 | python -m jenkins.pull_request_creator --repo-root=$GITHUB_WORKSPACE \ 55 | --target-branch="${{ env.target_branch }}" --base-branch-name="upgrade-python-requirements" \ 56 | --commit-message="chore: Updating Python Requirements" --pr-title="Python Requirements Update" \ 57 | --pr-body="Python requirements update.Please review the [changelogs](https://openedx.atlassian.net/wiki/spaces/TE/pages/1001521320/Python+Package+Changelogs) for the upgraded packages." \ 58 | --user-reviewers="" --team-reviewers="arbi-bom" --delete-old-pull-requests 59 | 60 | - name: Send failure notification 61 | if: ${{ failure() }} 62 | uses: dawidd6/action-send-mail@v3 63 | with: 64 | server_address: email-smtp.us-east-1.amazonaws.com 65 | server_port: 465 66 | username: ${{secrets.EDX_SMTP_USERNAME}} 67 | password: ${{secrets.EDX_SMTP_PASSWORD}} 68 | subject: Upgrade python requirements workflow failed in ${{github.repository}} 69 | to: arbi-bom@edx.org 70 | from: github-actions 71 | body: Upgrade python requirements workflow in ${{github.repository}} failed! For details see "github.com/${{ github.repository }}/actions/runs/${{ github.run_id }}" 72 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # .gitignore for edx-platform. 2 | # There's a lot here, please try to keep it organized. 3 | 4 | ### Python artifacts 5 | *.pyc 6 | 7 | ### Editor and IDE artifacts 8 | *~ 9 | *.swp 10 | *.orig 11 | /nbproject 12 | .idea/ 13 | .redcar/ 14 | codekit-config.json 15 | .pycharm_helpers/ 16 | 17 | ### NFS artifacts 18 | .nfs* 19 | 20 | ### OS X artifacts 21 | *.DS_Store 22 | .AppleDouble 23 | :2e_* 24 | :2e# 25 | 26 | ### Installation artifacts 27 | *.egg-info 28 | 29 | ### IPython Notebooks 30 | *.ipynb 31 | 32 | ### Pip artifacts 33 | python-libs/ 34 | 35 | ### Test artifacts 36 | .cache 37 | swagger-codegen-cli.jar 38 | swagger.yaml 39 | .swagger-codegen-ignore 40 | edx-api-stub-server/ 41 | swagger-build-artifacts/ 42 | venv 43 | -------------------------------------------------------------------------------- /.pep8: -------------------------------------------------------------------------------- 1 | [pep8] 2 | ignore=E501 3 | max_line_length=119 4 | exclude= 5 | -------------------------------------------------------------------------------- /.pylintrc: -------------------------------------------------------------------------------- 1 | [MAIN] 2 | 3 | # Analyse import fallback blocks. This can be used to support both Python 2 and 4 | # 3 compatible code, which means that the block might have code that exists 5 | # only in one or another interpreter, leading to false positives when analysed. 6 | analyse-fallback-blocks=no 7 | 8 | # Clear in-memory caches upon conclusion of linting. Useful if running pylint 9 | # in a server-like mode. 10 | clear-cache-post-run=no 11 | 12 | # Load and enable all available extensions. Use --list-extensions to see a list 13 | # all available extensions. 14 | #enable-all-extensions= 15 | 16 | # In error mode, messages with a category besides ERROR or FATAL are 17 | # suppressed, and no reports are done by default. Error mode is compatible with 18 | # disabling specific errors. 19 | #errors-only= 20 | 21 | # Always return a 0 (non-error) status code, even if lint errors are found. 22 | # This is primarily useful in continuous integration scripts. 23 | #exit-zero= 24 | 25 | # A comma-separated list of package or module names from where C extensions may 26 | # be loaded. Extensions are loading into the active Python interpreter and may 27 | # run arbitrary code. 28 | extension-pkg-allow-list= 29 | 30 | # A comma-separated list of package or module names from where C extensions may 31 | # be loaded. Extensions are loading into the active Python interpreter and may 32 | # run arbitrary code. (This is an alternative name to extension-pkg-allow-list 33 | # for backward compatibility.) 34 | extension-pkg-whitelist= 35 | 36 | # Return non-zero exit code if any of these messages/categories are detected, 37 | # even if score is above --fail-under value. Syntax same as enable. Messages 38 | # specified are enabled, while categories only check already-enabled messages. 39 | fail-on= 40 | 41 | # Specify a score threshold under which the program will exit with error. 42 | fail-under=10 43 | 44 | # Interpret the stdin as a python script, whose filename needs to be passed as 45 | # the module_or_package argument. 46 | #from-stdin= 47 | 48 | # Files or directories to be skipped. They should be base names, not paths. 49 | ignore=CVS 50 | 51 | # Add files or directories matching the regular expressions patterns to the 52 | # ignore-list. The regex matches against paths and can be in Posix or Windows 53 | # format. Because '\\' represents the directory delimiter on Windows systems, 54 | # it can't be used as an escape character. 55 | ignore-paths= 56 | 57 | # Files or directories matching the regular expression patterns are skipped. 58 | # The regex matches against base names, not paths. The default value ignores 59 | # Emacs file locks 60 | ignore-patterns=^\.# 61 | 62 | # List of module names for which member attributes should not be checked and 63 | # will not be imported (useful for modules/projects where namespaces are 64 | # manipulated during runtime and thus existing member attributes cannot be 65 | # deduced by static analysis). It supports qualified module names, as well as 66 | # Unix pattern matching. 67 | ignored-modules= 68 | 69 | # Python code to execute, usually for sys.path manipulation such as 70 | # pygtk.require(). 71 | #init-hook= 72 | 73 | # Use multiple processes to speed up Pylint. Specifying 0 will auto-detect the 74 | # number of processors available to use, and will cap the count on Windows to 75 | # avoid hangs. 76 | jobs=1 77 | 78 | # Control the amount of potential inferred values when inferring a single 79 | # object. This can help the performance when dealing with large functions or 80 | # complex, nested conditions. 81 | limit-inference-results=100 82 | 83 | # List of plugins (as comma separated values of python module names) to load, 84 | # usually to register additional checkers. 85 | load-plugins= 86 | 87 | # Pickle collected data for later comparisons. 88 | persistent=yes 89 | 90 | # Resolve imports to .pyi stubs if available. May reduce no-member messages and 91 | # increase not-an-iterable messages. 92 | prefer-stubs=no 93 | 94 | # Minimum Python version to use for version dependent checks. Will default to 95 | # the version used to run pylint. 96 | py-version=3.8 97 | 98 | # Discover python modules and packages in the file system subtree. 99 | recursive=no 100 | 101 | # Add paths to the list of the source roots. Supports globbing patterns. The 102 | # source root is an absolute path or a path relative to the current working 103 | # directory used to determine a package namespace for modules located under the 104 | # source root. 105 | source-roots= 106 | 107 | # When enabled, pylint would attempt to guess common misconfiguration and emit 108 | # user-friendly hints instead of false-positive error messages. 109 | suggestion-mode=yes 110 | 111 | # Allow loading of arbitrary C extensions. Extensions are imported into the 112 | # active Python interpreter and may run arbitrary code. 113 | unsafe-load-any-extension=no 114 | 115 | # In verbose mode, extra non-checker-related info will be displayed. 116 | #verbose= 117 | 118 | 119 | [BASIC] 120 | 121 | # Naming style matching correct argument names. 122 | argument-naming-style=snake_case 123 | 124 | # Regular expression matching correct argument names. Overrides argument- 125 | # naming-style. If left empty, argument names will be checked with the set 126 | # naming style. 127 | #argument-rgx= 128 | 129 | # Naming style matching correct attribute names. 130 | attr-naming-style=snake_case 131 | 132 | # Regular expression matching correct attribute names. Overrides attr-naming- 133 | # style. If left empty, attribute names will be checked with the set naming 134 | # style. 135 | #attr-rgx= 136 | 137 | # Bad variable names which should always be refused, separated by a comma. 138 | bad-names=foo, 139 | bar, 140 | baz, 141 | toto, 142 | tutu, 143 | tata 144 | 145 | # Bad variable names regexes, separated by a comma. If names match any regex, 146 | # they will always be refused 147 | bad-names-rgxs= 148 | 149 | # Naming style matching correct class attribute names. 150 | class-attribute-naming-style=any 151 | 152 | # Regular expression matching correct class attribute names. Overrides class- 153 | # attribute-naming-style. If left empty, class attribute names will be checked 154 | # with the set naming style. 155 | #class-attribute-rgx= 156 | 157 | # Naming style matching correct class constant names. 158 | class-const-naming-style=UPPER_CASE 159 | 160 | # Regular expression matching correct class constant names. Overrides class- 161 | # const-naming-style. If left empty, class constant names will be checked with 162 | # the set naming style. 163 | #class-const-rgx= 164 | 165 | # Naming style matching correct class names. 166 | class-naming-style=PascalCase 167 | 168 | # Regular expression matching correct class names. Overrides class-naming- 169 | # style. If left empty, class names will be checked with the set naming style. 170 | #class-rgx= 171 | 172 | # Naming style matching correct constant names. 173 | const-naming-style=UPPER_CASE 174 | 175 | # Regular expression matching correct constant names. Overrides const-naming- 176 | # style. If left empty, constant names will be checked with the set naming 177 | # style. 178 | #const-rgx= 179 | 180 | # Minimum line length for functions/classes that require docstrings, shorter 181 | # ones are exempt. 182 | docstring-min-length=-1 183 | 184 | # Naming style matching correct function names. 185 | function-naming-style=snake_case 186 | 187 | # Regular expression matching correct function names. Overrides function- 188 | # naming-style. If left empty, function names will be checked with the set 189 | # naming style. 190 | #function-rgx= 191 | 192 | # Good variable names which should always be accepted, separated by a comma. 193 | good-names=i, 194 | j, 195 | k, 196 | ex, 197 | Run, 198 | _ 199 | 200 | # Good variable names regexes, separated by a comma. If names match any regex, 201 | # they will always be accepted 202 | good-names-rgxs= 203 | 204 | # Include a hint for the correct naming format with invalid-name. 205 | include-naming-hint=no 206 | 207 | # Naming style matching correct inline iteration names. 208 | inlinevar-naming-style=any 209 | 210 | # Regular expression matching correct inline iteration names. Overrides 211 | # inlinevar-naming-style. If left empty, inline iteration names will be checked 212 | # with the set naming style. 213 | #inlinevar-rgx= 214 | 215 | # Naming style matching correct method names. 216 | method-naming-style=snake_case 217 | 218 | # Regular expression matching correct method names. Overrides method-naming- 219 | # style. If left empty, method names will be checked with the set naming style. 220 | #method-rgx= 221 | 222 | # Naming style matching correct module names. 223 | module-naming-style=snake_case 224 | 225 | # Regular expression matching correct module names. Overrides module-naming- 226 | # style. If left empty, module names will be checked with the set naming style. 227 | #module-rgx= 228 | 229 | # Colon-delimited sets of names that determine each other's naming style when 230 | # the name regexes allow several styles. 231 | name-group= 232 | 233 | # Regular expression which should only match function or class names that do 234 | # not require a docstring. 235 | no-docstring-rgx=^_ 236 | 237 | # List of decorators that produce properties, such as abc.abstractproperty. Add 238 | # to this list to register other decorators that produce valid properties. 239 | # These decorators are taken in consideration only for invalid-name. 240 | property-classes=abc.abstractproperty 241 | 242 | # Regular expression matching correct type alias names. If left empty, type 243 | # alias names will be checked with the set naming style. 244 | #typealias-rgx= 245 | 246 | # Regular expression matching correct type variable names. If left empty, type 247 | # variable names will be checked with the set naming style. 248 | #typevar-rgx= 249 | 250 | # Naming style matching correct variable names. 251 | variable-naming-style=snake_case 252 | 253 | # Regular expression matching correct variable names. Overrides variable- 254 | # naming-style. If left empty, variable names will be checked with the set 255 | # naming style. 256 | #variable-rgx= 257 | 258 | 259 | [CLASSES] 260 | 261 | # Warn about protected attribute access inside special methods 262 | check-protected-access-in-special-methods=no 263 | 264 | # List of method names used to declare (i.e. assign) instance attributes. 265 | defining-attr-methods=__init__, 266 | __new__, 267 | setUp, 268 | asyncSetUp, 269 | __post_init__ 270 | 271 | # List of member names, which should be excluded from the protected access 272 | # warning. 273 | exclude-protected=_asdict,_fields,_replace,_source,_make,os._exit 274 | 275 | # List of valid names for the first argument in a class method. 276 | valid-classmethod-first-arg=cls 277 | 278 | # List of valid names for the first argument in a metaclass class method. 279 | valid-metaclass-classmethod-first-arg=mcs 280 | 281 | 282 | [DESIGN] 283 | 284 | # List of regular expressions of class ancestor names to ignore when counting 285 | # public methods (see R0903) 286 | exclude-too-few-public-methods= 287 | 288 | # List of qualified class names to ignore when counting class parents (see 289 | # R0901) 290 | ignored-parents= 291 | 292 | # Maximum number of arguments for function / method. 293 | max-args=5 294 | 295 | # Maximum number of attributes for a class (see R0902). 296 | max-attributes=7 297 | 298 | # Maximum number of boolean expressions in an if statement (see R0916). 299 | max-bool-expr=5 300 | 301 | # Maximum number of branch for function / method body. 302 | max-branches=12 303 | 304 | # Maximum number of locals for function / method body. 305 | max-locals=15 306 | 307 | # Maximum number of parents for a class (see R0901). 308 | max-parents=7 309 | 310 | # Maximum number of public methods for a class (see R0904). 311 | max-public-methods=20 312 | 313 | # Maximum number of return / yield for function / method body. 314 | max-returns=6 315 | 316 | # Maximum number of statements in function / method body. 317 | max-statements=50 318 | 319 | # Minimum number of public methods for a class (see R0903). 320 | min-public-methods=2 321 | 322 | 323 | [EXCEPTIONS] 324 | 325 | # Exceptions that will emit a warning when caught. 326 | overgeneral-exceptions=builtins.BaseException,builtins.Exception 327 | 328 | 329 | [FORMAT] 330 | 331 | # Expected format of line ending, e.g. empty (any line ending), LF or CRLF. 332 | expected-line-ending-format= 333 | 334 | # Regexp for a line that is allowed to be longer than the limit. 335 | ignore-long-lines=^\s*(# )??$ 336 | 337 | # Number of spaces of indent required inside a hanging or continued line. 338 | indent-after-paren=4 339 | 340 | # String used as indentation unit. This is usually " " (4 spaces) or "\t" (1 341 | # tab). 342 | indent-string=' ' 343 | 344 | # Maximum number of characters on a single line. 345 | max-line-length=120 346 | 347 | # Maximum number of lines in a module. 348 | max-module-lines=1000 349 | 350 | # Allow the body of a class to be on the same line as the declaration if body 351 | # contains single statement. 352 | single-line-class-stmt=no 353 | 354 | # Allow the body of an if to be on the same line as the test if there is no 355 | # else. 356 | single-line-if-stmt=no 357 | 358 | 359 | [IMPORTS] 360 | 361 | # List of modules that can be imported at any level, not just the top level 362 | # one. 363 | allow-any-import-level= 364 | 365 | # Allow explicit reexports by alias from a package __init__. 366 | allow-reexport-from-package=no 367 | 368 | # Allow wildcard imports from modules that define __all__. 369 | allow-wildcard-with-all=no 370 | 371 | # Deprecated modules which should not be used, separated by a comma. 372 | deprecated-modules= 373 | 374 | # Output a graph (.gv or any supported image format) of external dependencies 375 | # to the given file (report RP0402 must not be disabled). 376 | ext-import-graph= 377 | 378 | # Output a graph (.gv or any supported image format) of all (i.e. internal and 379 | # external) dependencies to the given file (report RP0402 must not be 380 | # disabled). 381 | import-graph= 382 | 383 | # Output a graph (.gv or any supported image format) of internal dependencies 384 | # to the given file (report RP0402 must not be disabled). 385 | int-import-graph= 386 | 387 | # Force import order to recognize a module as part of the standard 388 | # compatibility libraries. 389 | known-standard-library= 390 | 391 | # Force import order to recognize a module as part of a third party library. 392 | known-third-party=enchant 393 | 394 | # Couples of modules and preferred modules, separated by a comma. 395 | preferred-modules= 396 | 397 | 398 | [LOGGING] 399 | 400 | # The type of string formatting that logging methods do. `old` means using % 401 | # formatting, `new` is for `{}` formatting. 402 | logging-format-style=old 403 | 404 | # Logging modules to check that the string format arguments are in logging 405 | # function parameter format. 406 | logging-modules=logging 407 | 408 | 409 | [MESSAGES CONTROL] 410 | 411 | # Only show warnings with the listed confidence levels. Leave empty to show 412 | # all. Valid levels: HIGH, CONTROL_FLOW, INFERENCE, INFERENCE_FAILURE, 413 | # UNDEFINED. 414 | confidence=HIGH, 415 | CONTROL_FLOW, 416 | INFERENCE, 417 | INFERENCE_FAILURE, 418 | UNDEFINED 419 | 420 | # Disable the message, report, category or checker with the given id(s). You 421 | # can either give multiple identifiers separated by comma (,) or put this 422 | # option multiple times (only on the command line, not in the configuration 423 | # file where it should appear only once). You can also use "--disable=all" to 424 | # disable everything first and then re-enable specific checks. For example, if 425 | # you want to run only the similarities checker, you can use "--disable=all 426 | # --enable=similarities". If you want to run only the classes checker, but have 427 | # no Warning level messages displayed, use "--disable=all --enable=classes 428 | # --disable=W". 429 | disable=raw-checker-failed, 430 | bad-inline-option, 431 | locally-disabled, 432 | file-ignored, 433 | suppressed-message, 434 | useless-suppression, 435 | deprecated-pragma, 436 | too-many-arguments, 437 | use-symbolic-message-instead, 438 | use-implicit-booleaness-not-comparison-to-string, 439 | use-implicit-booleaness-not-comparison-to-zero 440 | 441 | # Enable the message, report, category or checker with the given id(s). You can 442 | # either give multiple identifier separated by comma (,) or put this option 443 | # multiple time (only on the command line, not in the configuration file where 444 | # it should appear only once). See also the "--disable" option for examples. 445 | enable= 446 | 447 | 448 | [METHOD_ARGS] 449 | 450 | # List of qualified names (i.e., library.method) which require a timeout 451 | # parameter e.g. 'requests.api.get,requests.api.post' 452 | timeout-methods=requests.api.delete,requests.api.get,requests.api.head,requests.api.options,requests.api.patch,requests.api.post,requests.api.put,requests.api.request 453 | 454 | 455 | [MISCELLANEOUS] 456 | 457 | # List of note tags to take in consideration, separated by a comma. 458 | notes=FIXME, 459 | XXX, 460 | TODO 461 | 462 | # Regular expression of note tags to take in consideration. 463 | notes-rgx= 464 | 465 | 466 | [REFACTORING] 467 | 468 | # Maximum number of nested blocks for function / method body 469 | max-nested-blocks=5 470 | 471 | # Complete name of functions that never returns. When checking for 472 | # inconsistent-return-statements if a never returning function is called then 473 | # it will be considered as an explicit return statement and no message will be 474 | # printed. 475 | never-returning-functions=sys.exit,argparse.parse_error 476 | 477 | # Let 'consider-using-join' be raised when the separator to join on would be 478 | # non-empty (resulting in expected fixes of the type: ``"- " + " - 479 | # ".join(items)``) 480 | suggest-join-with-non-empty-separator=yes 481 | 482 | 483 | [REPORTS] 484 | 485 | # Python expression which should return a score less than or equal to 10. You 486 | # have access to the variables 'fatal', 'error', 'warning', 'refactor', 487 | # 'convention', and 'info' which contain the number of messages in each 488 | # category, as well as 'statement' which is the total number of statements 489 | # analyzed. This score is used by the global evaluation report (RP0004). 490 | evaluation=max(0, 0 if fatal else 10.0 - ((float(5 * error + warning + refactor + convention) / statement) * 10)) 491 | 492 | # Template used to display messages. This is a python new-style format string 493 | # used to format the message information. See doc for all details. 494 | msg-template= 495 | 496 | # Set the output format. Available formats are: text, parseable, colorized, 497 | # json2 (improved json format), json (old json format) and msvs (visual 498 | # studio). You can also give a reporter class, e.g. 499 | # mypackage.mymodule.MyReporterClass. 500 | #output-format= 501 | 502 | # Tells whether to display a full report or only the messages. 503 | reports=no 504 | 505 | # Activate the evaluation score. 506 | score=yes 507 | 508 | 509 | [SIMILARITIES] 510 | 511 | # Comments are removed from the similarity computation 512 | ignore-comments=yes 513 | 514 | # Docstrings are removed from the similarity computation 515 | ignore-docstrings=yes 516 | 517 | # Imports are removed from the similarity computation 518 | ignore-imports=yes 519 | 520 | # Signatures are removed from the similarity computation 521 | ignore-signatures=yes 522 | 523 | # Minimum lines number of a similarity. 524 | min-similarity-lines=4 525 | 526 | 527 | [SPELLING] 528 | 529 | # Limits count of emitted suggestions for spelling mistakes. 530 | max-spelling-suggestions=4 531 | 532 | # Spelling dictionary name. No available dictionaries : You need to install 533 | # both the python package and the system dependency for enchant to work. 534 | spelling-dict= 535 | 536 | # List of comma separated words that should be considered directives if they 537 | # appear at the beginning of a comment and should not be checked. 538 | spelling-ignore-comment-directives=fmt: on,fmt: off,noqa:,noqa,nosec,isort:skip,mypy: 539 | 540 | # List of comma separated words that should not be checked. 541 | spelling-ignore-words= 542 | 543 | # A path to a file that contains the private dictionary; one word per line. 544 | spelling-private-dict-file= 545 | 546 | # Tells whether to store unknown words to the private dictionary (see the 547 | # --spelling-private-dict-file option) instead of raising a message. 548 | spelling-store-unknown-words=no 549 | 550 | 551 | [STRING] 552 | 553 | # This flag controls whether inconsistent-quotes generates a warning when the 554 | # character used as a quote delimiter is used inconsistently within a module. 555 | check-quote-consistency=no 556 | 557 | # This flag controls whether the implicit-str-concat should generate a warning 558 | # on implicit string concatenation in sequences defined over several lines. 559 | check-str-concat-over-line-jumps=no 560 | 561 | 562 | [TYPECHECK] 563 | 564 | # List of decorators that produce context managers, such as 565 | # contextlib.contextmanager. Add to this list to register other decorators that 566 | # produce valid context managers. 567 | contextmanager-decorators=contextlib.contextmanager 568 | 569 | # List of members which are set dynamically and missed by pylint inference 570 | # system, and so shouldn't trigger E1101 when accessed. Python regular 571 | # expressions are accepted. 572 | generated-members= 573 | 574 | # Tells whether to warn about missing members when the owner of the attribute 575 | # is inferred to be None. 576 | ignore-none=yes 577 | 578 | # This flag controls whether pylint should warn about no-member and similar 579 | # checks whenever an opaque object is returned when inferring. The inference 580 | # can return multiple potential results while evaluating a Python object, but 581 | # some branches might not be evaluated, which results in partial inference. In 582 | # that case, it might be useful to still emit no-member and other checks for 583 | # the rest of the inferred objects. 584 | ignore-on-opaque-inference=yes 585 | 586 | # List of symbolic message names to ignore for Mixin members. 587 | ignored-checks-for-mixins=no-member, 588 | not-async-context-manager, 589 | not-context-manager, 590 | attribute-defined-outside-init 591 | 592 | # List of class names for which member attributes should not be checked (useful 593 | # for classes with dynamically set attributes). This supports the use of 594 | # qualified names. 595 | ignored-classes=optparse.Values,thread._local,_thread._local,argparse.Namespace 596 | 597 | # Show a hint with possible names when a member name was not found. The aspect 598 | # of finding the hint is based on edit distance. 599 | missing-member-hint=yes 600 | 601 | # The minimum edit distance a name should have in order to be considered a 602 | # similar match for a missing member name. 603 | missing-member-hint-distance=1 604 | 605 | # The total number of similar names that should be taken in consideration when 606 | # showing a hint for a missing member. 607 | missing-member-max-choices=1 608 | 609 | # Regex pattern to define which classes are considered mixins. 610 | mixin-class-rgx=.*[Mm]ixin 611 | 612 | # List of decorators that change the signature of a decorated function. 613 | signature-mutators= 614 | 615 | 616 | [VARIABLES] 617 | 618 | # List of additional names supposed to be defined in builtins. Remember that 619 | # you should avoid defining new builtins when possible. 620 | additional-builtins= 621 | 622 | # Tells whether unused global variables should be treated as a violation. 623 | allow-global-unused-variables=yes 624 | 625 | # List of names allowed to shadow builtins 626 | allowed-redefined-builtins= 627 | 628 | # List of strings which can identify a callback function by name. A callback 629 | # name must start or end with one of those strings. 630 | callbacks=cb_, 631 | _cb 632 | 633 | # A regular expression matching the name of dummy variables (i.e. expected to 634 | # not be used). 635 | dummy-variables-rgx=_+$|(_[a-zA-Z0-9_]*[a-zA-Z0-9]+?$)|dummy|^ignored_|^unused_ 636 | 637 | # Argument names that match this expression will be ignored. 638 | ignored-argument-names=_.*|^ignored_|^unused_ 639 | 640 | # Tells whether we should check for unused import in __init__ files. 641 | init-import=no 642 | 643 | # List of qualified module names which can have objects that can redefine 644 | # builtins. 645 | redefining-builtins-modules=six.moves,past.builtins,future.builtins,builtins,io 646 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU AFFERO GENERAL PUBLIC LICENSE 2 | Version 3, 19 November 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU Affero General Public License is a free, copyleft license for 11 | software and other kinds of works, specifically designed to ensure 12 | cooperation with the community in the case of network server software. 13 | 14 | The licenses for most software and other practical works are designed 15 | to take away your freedom to share and change the works. By contrast, 16 | our General Public Licenses are intended to guarantee your freedom to 17 | share and change all versions of a program--to make sure it remains free 18 | software for all its users. 19 | 20 | When we speak of free software, we are referring to freedom, not 21 | price. Our General Public Licenses are designed to make sure that you 22 | have the freedom to distribute copies of free software (and charge for 23 | them if you wish), that you receive source code or can get it if you 24 | want it, that you can change the software or use pieces of it in new 25 | free programs, and that you know you can do these things. 26 | 27 | Developers that use our General Public Licenses protect your rights 28 | with two steps: (1) assert copyright on the software, and (2) offer 29 | you this License which gives you legal permission to copy, distribute 30 | and/or modify the software. 31 | 32 | A secondary benefit of defending all users' freedom is that 33 | improvements made in alternate versions of the program, if they 34 | receive widespread use, become available for other developers to 35 | incorporate. Many developers of free software are heartened and 36 | encouraged by the resulting cooperation. However, in the case of 37 | software used on network servers, this result may fail to come about. 38 | The GNU General Public License permits making a modified version and 39 | letting the public access it on a server without ever releasing its 40 | source code to the public. 41 | 42 | The GNU Affero General Public License is designed specifically to 43 | ensure that, in such cases, the modified source code becomes available 44 | to the community. It requires the operator of a network server to 45 | provide the source code of the modified version running there to the 46 | users of that server. Therefore, public use of a modified version, on 47 | a publicly accessible server, gives the public access to the source 48 | code of the modified version. 49 | 50 | An older license, called the Affero General Public License and 51 | published by Affero, was designed to accomplish similar goals. This is 52 | a different license, not a version of the Affero GPL, but Affero has 53 | released a new version of the Affero GPL which permits relicensing under 54 | this license. 55 | 56 | The precise terms and conditions for copying, distribution and 57 | modification follow. 58 | 59 | TERMS AND CONDITIONS 60 | 61 | 0. Definitions. 62 | 63 | "This License" refers to version 3 of the GNU Affero General Public License. 64 | 65 | "Copyright" also means copyright-like laws that apply to other kinds of 66 | works, such as semiconductor masks. 67 | 68 | "The Program" refers to any copyrightable work licensed under this 69 | License. Each licensee is addressed as "you". "Licensees" and 70 | "recipients" may be individuals or organizations. 71 | 72 | To "modify" a work means to copy from or adapt all or part of the work 73 | in a fashion requiring copyright permission, other than the making of an 74 | exact copy. The resulting work is called a "modified version" of the 75 | earlier work or a work "based on" the earlier work. 76 | 77 | A "covered work" means either the unmodified Program or a work based 78 | on the Program. 79 | 80 | To "propagate" a work means to do anything with it that, without 81 | permission, would make you directly or secondarily liable for 82 | infringement under applicable copyright law, except executing it on a 83 | computer or modifying a private copy. Propagation includes copying, 84 | distribution (with or without modification), making available to the 85 | public, and in some countries other activities as well. 86 | 87 | To "convey" a work means any kind of propagation that enables other 88 | parties to make or receive copies. Mere interaction with a user through 89 | a computer network, with no transfer of a copy, is not conveying. 90 | 91 | An interactive user interface displays "Appropriate Legal Notices" 92 | to the extent that it includes a convenient and prominently visible 93 | feature that (1) displays an appropriate copyright notice, and (2) 94 | tells the user that there is no warranty for the work (except to the 95 | extent that warranties are provided), that licensees may convey the 96 | work under this License, and how to view a copy of this License. If 97 | the interface presents a list of user commands or options, such as a 98 | menu, a prominent item in the list meets this criterion. 99 | 100 | 1. Source Code. 101 | 102 | The "source code" for a work means the preferred form of the work 103 | for making modifications to it. "Object code" means any non-source 104 | form of a work. 105 | 106 | A "Standard Interface" means an interface that either is an official 107 | standard defined by a recognized standards body, or, in the case of 108 | interfaces specified for a particular programming language, one that 109 | is widely used among developers working in that language. 110 | 111 | The "System Libraries" of an executable work include anything, other 112 | than the work as a whole, that (a) is included in the normal form of 113 | packaging a Major Component, but which is not part of that Major 114 | Component, and (b) serves only to enable use of the work with that 115 | Major Component, or to implement a Standard Interface for which an 116 | implementation is available to the public in source code form. A 117 | "Major Component", in this context, means a major essential component 118 | (kernel, window system, and so on) of the specific operating system 119 | (if any) on which the executable work runs, or a compiler used to 120 | produce the work, or an object code interpreter used to run it. 121 | 122 | The "Corresponding Source" for a work in object code form means all 123 | the source code needed to generate, install, and (for an executable 124 | work) run the object code and to modify the work, including scripts to 125 | control those activities. However, it does not include the work's 126 | System Libraries, or general-purpose tools or generally available free 127 | programs which are used unmodified in performing those activities but 128 | which are not part of the work. For example, Corresponding Source 129 | includes interface definition files associated with source files for 130 | the work, and the source code for shared libraries and dynamically 131 | linked subprograms that the work is specifically designed to require, 132 | such as by intimate data communication or control flow between those 133 | subprograms and other parts of the work. 134 | 135 | The Corresponding Source need not include anything that users 136 | can regenerate automatically from other parts of the Corresponding 137 | Source. 138 | 139 | The Corresponding Source for a work in source code form is that 140 | same work. 141 | 142 | 2. Basic Permissions. 143 | 144 | All rights granted under this License are granted for the term of 145 | copyright on the Program, and are irrevocable provided the stated 146 | conditions are met. This License explicitly affirms your unlimited 147 | permission to run the unmodified Program. The output from running a 148 | covered work is covered by this License only if the output, given its 149 | content, constitutes a covered work. This License acknowledges your 150 | rights of fair use or other equivalent, as provided by copyright law. 151 | 152 | You may make, run and propagate covered works that you do not 153 | convey, without conditions so long as your license otherwise remains 154 | in force. You may convey covered works to others for the sole purpose 155 | of having them make modifications exclusively for you, or provide you 156 | with facilities for running those works, provided that you comply with 157 | the terms of this License in conveying all material for which you do 158 | not control copyright. Those thus making or running the covered works 159 | for you must do so exclusively on your behalf, under your direction 160 | and control, on terms that prohibit them from making any copies of 161 | your copyrighted material outside their relationship with you. 162 | 163 | Conveying under any other circumstances is permitted solely under 164 | the conditions stated below. Sublicensing is not allowed; section 10 165 | makes it unnecessary. 166 | 167 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 168 | 169 | No covered work shall be deemed part of an effective technological 170 | measure under any applicable law fulfilling obligations under article 171 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 172 | similar laws prohibiting or restricting circumvention of such 173 | measures. 174 | 175 | When you convey a covered work, you waive any legal power to forbid 176 | circumvention of technological measures to the extent such circumvention 177 | is effected by exercising rights under this License with respect to 178 | the covered work, and you disclaim any intention to limit operation or 179 | modification of the work as a means of enforcing, against the work's 180 | users, your or third parties' legal rights to forbid circumvention of 181 | technological measures. 182 | 183 | 4. Conveying Verbatim Copies. 184 | 185 | You may convey verbatim copies of the Program's source code as you 186 | receive it, in any medium, provided that you conspicuously and 187 | appropriately publish on each copy an appropriate copyright notice; 188 | keep intact all notices stating that this License and any 189 | non-permissive terms added in accord with section 7 apply to the code; 190 | keep intact all notices of the absence of any warranty; and give all 191 | recipients a copy of this License along with the Program. 192 | 193 | You may charge any price or no price for each copy that you convey, 194 | and you may offer support or warranty protection for a fee. 195 | 196 | 5. Conveying Modified Source Versions. 197 | 198 | You may convey a work based on the Program, or the modifications to 199 | produce it from the Program, in the form of source code under the 200 | terms of section 4, provided that you also meet all of these conditions: 201 | 202 | a) The work must carry prominent notices stating that you modified 203 | it, and giving a relevant date. 204 | 205 | b) The work must carry prominent notices stating that it is 206 | released under this License and any conditions added under section 207 | 7. This requirement modifies the requirement in section 4 to 208 | "keep intact all notices". 209 | 210 | c) You must license the entire work, as a whole, under this 211 | License to anyone who comes into possession of a copy. This 212 | License will therefore apply, along with any applicable section 7 213 | additional terms, to the whole of the work, and all its parts, 214 | regardless of how they are packaged. This License gives no 215 | permission to license the work in any other way, but it does not 216 | invalidate such permission if you have separately received it. 217 | 218 | d) If the work has interactive user interfaces, each must display 219 | Appropriate Legal Notices; however, if the Program has interactive 220 | interfaces that do not display Appropriate Legal Notices, your 221 | work need not make them do so. 222 | 223 | A compilation of a covered work with other separate and independent 224 | works, which are not by their nature extensions of the covered work, 225 | and which are not combined with it such as to form a larger program, 226 | in or on a volume of a storage or distribution medium, is called an 227 | "aggregate" if the compilation and its resulting copyright are not 228 | used to limit the access or legal rights of the compilation's users 229 | beyond what the individual works permit. Inclusion of a covered work 230 | in an aggregate does not cause this License to apply to the other 231 | parts of the aggregate. 232 | 233 | 6. Conveying Non-Source Forms. 234 | 235 | You may convey a covered work in object code form under the terms 236 | of sections 4 and 5, provided that you also convey the 237 | machine-readable Corresponding Source under the terms of this License, 238 | in one of these ways: 239 | 240 | a) Convey the object code in, or embodied in, a physical product 241 | (including a physical distribution medium), accompanied by the 242 | Corresponding Source fixed on a durable physical medium 243 | customarily used for software interchange. 244 | 245 | b) Convey the object code in, or embodied in, a physical product 246 | (including a physical distribution medium), accompanied by a 247 | written offer, valid for at least three years and valid for as 248 | long as you offer spare parts or customer support for that product 249 | model, to give anyone who possesses the object code either (1) a 250 | copy of the Corresponding Source for all the software in the 251 | product that is covered by this License, on a durable physical 252 | medium customarily used for software interchange, for a price no 253 | more than your reasonable cost of physically performing this 254 | conveying of source, or (2) access to copy the 255 | Corresponding Source from a network server at no charge. 256 | 257 | c) Convey individual copies of the object code with a copy of the 258 | written offer to provide the Corresponding Source. This 259 | alternative is allowed only occasionally and noncommercially, and 260 | only if you received the object code with such an offer, in accord 261 | with subsection 6b. 262 | 263 | d) Convey the object code by offering access from a designated 264 | place (gratis or for a charge), and offer equivalent access to the 265 | Corresponding Source in the same way through the same place at no 266 | further charge. You need not require recipients to copy the 267 | Corresponding Source along with the object code. If the place to 268 | copy the object code is a network server, the Corresponding Source 269 | may be on a different server (operated by you or a third party) 270 | that supports equivalent copying facilities, provided you maintain 271 | clear directions next to the object code saying where to find the 272 | Corresponding Source. Regardless of what server hosts the 273 | Corresponding Source, you remain obligated to ensure that it is 274 | available for as long as needed to satisfy these requirements. 275 | 276 | e) Convey the object code using peer-to-peer transmission, provided 277 | you inform other peers where the object code and Corresponding 278 | Source of the work are being offered to the general public at no 279 | charge under subsection 6d. 280 | 281 | A separable portion of the object code, whose source code is excluded 282 | from the Corresponding Source as a System Library, need not be 283 | included in conveying the object code work. 284 | 285 | A "User Product" is either (1) a "consumer product", which means any 286 | tangible personal property which is normally used for personal, family, 287 | or household purposes, or (2) anything designed or sold for incorporation 288 | into a dwelling. In determining whether a product is a consumer product, 289 | doubtful cases shall be resolved in favor of coverage. For a particular 290 | product received by a particular user, "normally used" refers to a 291 | typical or common use of that class of product, regardless of the status 292 | of the particular user or of the way in which the particular user 293 | actually uses, or expects or is expected to use, the product. A product 294 | is a consumer product regardless of whether the product has substantial 295 | commercial, industrial or non-consumer uses, unless such uses represent 296 | the only significant mode of use of the product. 297 | 298 | "Installation Information" for a User Product means any methods, 299 | procedures, authorization keys, or other information required to install 300 | and execute modified versions of a covered work in that User Product from 301 | a modified version of its Corresponding Source. The information must 302 | suffice to ensure that the continued functioning of the modified object 303 | code is in no case prevented or interfered with solely because 304 | modification has been made. 305 | 306 | If you convey an object code work under this section in, or with, or 307 | specifically for use in, a User Product, and the conveying occurs as 308 | part of a transaction in which the right of possession and use of the 309 | User Product is transferred to the recipient in perpetuity or for a 310 | fixed term (regardless of how the transaction is characterized), the 311 | Corresponding Source conveyed under this section must be accompanied 312 | by the Installation Information. But this requirement does not apply 313 | if neither you nor any third party retains the ability to install 314 | modified object code on the User Product (for example, the work has 315 | been installed in ROM). 316 | 317 | The requirement to provide Installation Information does not include a 318 | requirement to continue to provide support service, warranty, or updates 319 | for a work that has been modified or installed by the recipient, or for 320 | the User Product in which it has been modified or installed. Access to a 321 | network may be denied when the modification itself materially and 322 | adversely affects the operation of the network or violates the rules and 323 | protocols for communication across the network. 324 | 325 | Corresponding Source conveyed, and Installation Information provided, 326 | in accord with this section must be in a format that is publicly 327 | documented (and with an implementation available to the public in 328 | source code form), and must require no special password or key for 329 | unpacking, reading or copying. 330 | 331 | 7. Additional Terms. 332 | 333 | "Additional permissions" are terms that supplement the terms of this 334 | License by making exceptions from one or more of its conditions. 335 | Additional permissions that are applicable to the entire Program shall 336 | be treated as though they were included in this License, to the extent 337 | that they are valid under applicable law. If additional permissions 338 | apply only to part of the Program, that part may be used separately 339 | under those permissions, but the entire Program remains governed by 340 | this License without regard to the additional permissions. 341 | 342 | When you convey a copy of a covered work, you may at your option 343 | remove any additional permissions from that copy, or from any part of 344 | it. (Additional permissions may be written to require their own 345 | removal in certain cases when you modify the work.) You may place 346 | additional permissions on material, added by you to a covered work, 347 | for which you have or can give appropriate copyright permission. 348 | 349 | Notwithstanding any other provision of this License, for material you 350 | add to a covered work, you may (if authorized by the copyright holders of 351 | that material) supplement the terms of this License with terms: 352 | 353 | a) Disclaiming warranty or limiting liability differently from the 354 | terms of sections 15 and 16 of this License; or 355 | 356 | b) Requiring preservation of specified reasonable legal notices or 357 | author attributions in that material or in the Appropriate Legal 358 | Notices displayed by works containing it; or 359 | 360 | c) Prohibiting misrepresentation of the origin of that material, or 361 | requiring that modified versions of such material be marked in 362 | reasonable ways as different from the original version; or 363 | 364 | d) Limiting the use for publicity purposes of names of licensors or 365 | authors of the material; or 366 | 367 | e) Declining to grant rights under trademark law for use of some 368 | trade names, trademarks, or service marks; or 369 | 370 | f) Requiring indemnification of licensors and authors of that 371 | material by anyone who conveys the material (or modified versions of 372 | it) with contractual assumptions of liability to the recipient, for 373 | any liability that these contractual assumptions directly impose on 374 | those licensors and authors. 375 | 376 | All other non-permissive additional terms are considered "further 377 | restrictions" within the meaning of section 10. If the Program as you 378 | received it, or any part of it, contains a notice stating that it is 379 | governed by this License along with a term that is a further 380 | restriction, you may remove that term. If a license document contains 381 | a further restriction but permits relicensing or conveying under this 382 | License, you may add to a covered work material governed by the terms 383 | of that license document, provided that the further restriction does 384 | not survive such relicensing or conveying. 385 | 386 | If you add terms to a covered work in accord with this section, you 387 | must place, in the relevant source files, a statement of the 388 | additional terms that apply to those files, or a notice indicating 389 | where to find the applicable terms. 390 | 391 | Additional terms, permissive or non-permissive, may be stated in the 392 | form of a separately written license, or stated as exceptions; 393 | the above requirements apply either way. 394 | 395 | 8. Termination. 396 | 397 | You may not propagate or modify a covered work except as expressly 398 | provided under this License. Any attempt otherwise to propagate or 399 | modify it is void, and will automatically terminate your rights under 400 | this License (including any patent licenses granted under the third 401 | paragraph of section 11). 402 | 403 | However, if you cease all violation of this License, then your 404 | license from a particular copyright holder is reinstated (a) 405 | provisionally, unless and until the copyright holder explicitly and 406 | finally terminates your license, and (b) permanently, if the copyright 407 | holder fails to notify you of the violation by some reasonable means 408 | prior to 60 days after the cessation. 409 | 410 | Moreover, your license from a particular copyright holder is 411 | reinstated permanently if the copyright holder notifies you of the 412 | violation by some reasonable means, this is the first time you have 413 | received notice of violation of this License (for any work) from that 414 | copyright holder, and you cure the violation prior to 30 days after 415 | your receipt of the notice. 416 | 417 | Termination of your rights under this section does not terminate the 418 | licenses of parties who have received copies or rights from you under 419 | this License. If your rights have been terminated and not permanently 420 | reinstated, you do not qualify to receive new licenses for the same 421 | material under section 10. 422 | 423 | 9. Acceptance Not Required for Having Copies. 424 | 425 | You are not required to accept this License in order to receive or 426 | run a copy of the Program. Ancillary propagation of a covered work 427 | occurring solely as a consequence of using peer-to-peer transmission 428 | to receive a copy likewise does not require acceptance. However, 429 | nothing other than this License grants you permission to propagate or 430 | modify any covered work. These actions infringe copyright if you do 431 | not accept this License. Therefore, by modifying or propagating a 432 | covered work, you indicate your acceptance of this License to do so. 433 | 434 | 10. Automatic Licensing of Downstream Recipients. 435 | 436 | Each time you convey a covered work, the recipient automatically 437 | receives a license from the original licensors, to run, modify and 438 | propagate that work, subject to this License. You are not responsible 439 | for enforcing compliance by third parties with this License. 440 | 441 | An "entity transaction" is a transaction transferring control of an 442 | organization, or substantially all assets of one, or subdividing an 443 | organization, or merging organizations. If propagation of a covered 444 | work results from an entity transaction, each party to that 445 | transaction who receives a copy of the work also receives whatever 446 | licenses to the work the party's predecessor in interest had or could 447 | give under the previous paragraph, plus a right to possession of the 448 | Corresponding Source of the work from the predecessor in interest, if 449 | the predecessor has it or can get it with reasonable efforts. 450 | 451 | You may not impose any further restrictions on the exercise of the 452 | rights granted or affirmed under this License. For example, you may 453 | not impose a license fee, royalty, or other charge for exercise of 454 | rights granted under this License, and you may not initiate litigation 455 | (including a cross-claim or counterclaim in a lawsuit) alleging that 456 | any patent claim is infringed by making, using, selling, offering for 457 | sale, or importing the Program or any portion of it. 458 | 459 | 11. Patents. 460 | 461 | A "contributor" is a copyright holder who authorizes use under this 462 | License of the Program or a work on which the Program is based. The 463 | work thus licensed is called the contributor's "contributor version". 464 | 465 | A contributor's "essential patent claims" are all patent claims 466 | owned or controlled by the contributor, whether already acquired or 467 | hereafter acquired, that would be infringed by some manner, permitted 468 | by this License, of making, using, or selling its contributor version, 469 | but do not include claims that would be infringed only as a 470 | consequence of further modification of the contributor version. For 471 | purposes of this definition, "control" includes the right to grant 472 | patent sublicenses in a manner consistent with the requirements of 473 | this License. 474 | 475 | Each contributor grants you a non-exclusive, worldwide, royalty-free 476 | patent license under the contributor's essential patent claims, to 477 | make, use, sell, offer for sale, import and otherwise run, modify and 478 | propagate the contents of its contributor version. 479 | 480 | In the following three paragraphs, a "patent license" is any express 481 | agreement or commitment, however denominated, not to enforce a patent 482 | (such as an express permission to practice a patent or covenant not to 483 | sue for patent infringement). To "grant" such a patent license to a 484 | party means to make such an agreement or commitment not to enforce a 485 | patent against the party. 486 | 487 | If you convey a covered work, knowingly relying on a patent license, 488 | and the Corresponding Source of the work is not available for anyone 489 | to copy, free of charge and under the terms of this License, through a 490 | publicly available network server or other readily accessible means, 491 | then you must either (1) cause the Corresponding Source to be so 492 | available, or (2) arrange to deprive yourself of the benefit of the 493 | patent license for this particular work, or (3) arrange, in a manner 494 | consistent with the requirements of this License, to extend the patent 495 | license to downstream recipients. "Knowingly relying" means you have 496 | actual knowledge that, but for the patent license, your conveying the 497 | covered work in a country, or your recipient's use of the covered work 498 | in a country, would infringe one or more identifiable patents in that 499 | country that you have reason to believe are valid. 500 | 501 | If, pursuant to or in connection with a single transaction or 502 | arrangement, you convey, or propagate by procuring conveyance of, a 503 | covered work, and grant a patent license to some of the parties 504 | receiving the covered work authorizing them to use, propagate, modify 505 | or convey a specific copy of the covered work, then the patent license 506 | you grant is automatically extended to all recipients of the covered 507 | work and works based on it. 508 | 509 | A patent license is "discriminatory" if it does not include within 510 | the scope of its coverage, prohibits the exercise of, or is 511 | conditioned on the non-exercise of one or more of the rights that are 512 | specifically granted under this License. You may not convey a covered 513 | work if you are a party to an arrangement with a third party that is 514 | in the business of distributing software, under which you make payment 515 | to the third party based on the extent of your activity of conveying 516 | the work, and under which the third party grants, to any of the 517 | parties who would receive the covered work from you, a discriminatory 518 | patent license (a) in connection with copies of the covered work 519 | conveyed by you (or copies made from those copies), or (b) primarily 520 | for and in connection with specific products or compilations that 521 | contain the covered work, unless you entered into that arrangement, 522 | or that patent license was granted, prior to 28 March 2007. 523 | 524 | Nothing in this License shall be construed as excluding or limiting 525 | any implied license or other defenses to infringement that may 526 | otherwise be available to you under applicable patent law. 527 | 528 | 12. No Surrender of Others' Freedom. 529 | 530 | If conditions are imposed on you (whether by court order, agreement or 531 | otherwise) that contradict the conditions of this License, they do not 532 | excuse you from the conditions of this License. If you cannot convey a 533 | covered work so as to satisfy simultaneously your obligations under this 534 | License and any other pertinent obligations, then as a consequence you may 535 | not convey it at all. For example, if you agree to terms that obligate you 536 | to collect a royalty for further conveying from those to whom you convey 537 | the Program, the only way you could satisfy both those terms and this 538 | License would be to refrain entirely from conveying the Program. 539 | 540 | 13. Remote Network Interaction; Use with the GNU General Public License. 541 | 542 | Notwithstanding any other provision of this License, if you modify the 543 | Program, your modified version must prominently offer all users 544 | interacting with it remotely through a computer network (if your version 545 | supports such interaction) an opportunity to receive the Corresponding 546 | Source of your version by providing access to the Corresponding Source 547 | from a network server at no charge, through some standard or customary 548 | means of facilitating copying of software. This Corresponding Source 549 | shall include the Corresponding Source for any work covered by version 3 550 | of the GNU General Public License that is incorporated pursuant to the 551 | following paragraph. 552 | 553 | Notwithstanding any other provision of this License, you have 554 | permission to link or combine any covered work with a work licensed 555 | under version 3 of the GNU General Public License into a single 556 | combined work, and to convey the resulting work. The terms of this 557 | License will continue to apply to the part which is the covered work, 558 | but the work with which it is combined will remain governed by version 559 | 3 of the GNU General Public License. 560 | 561 | 14. Revised Versions of this License. 562 | 563 | The Free Software Foundation may publish revised and/or new versions of 564 | the GNU Affero General Public License from time to time. Such new versions 565 | will be similar in spirit to the present version, but may differ in detail to 566 | address new problems or concerns. 567 | 568 | Each version is given a distinguishing version number. If the 569 | Program specifies that a certain numbered version of the GNU Affero General 570 | Public License "or any later version" applies to it, you have the 571 | option of following the terms and conditions either of that numbered 572 | version or of any later version published by the Free Software 573 | Foundation. If the Program does not specify a version number of the 574 | GNU Affero General Public License, you may choose any version ever published 575 | by the Free Software Foundation. 576 | 577 | If the Program specifies that a proxy can decide which future 578 | versions of the GNU Affero General Public License can be used, that proxy's 579 | public statement of acceptance of a version permanently authorizes you 580 | to choose that version for the Program. 581 | 582 | Later license versions may give you additional or different 583 | permissions. However, no additional obligations are imposed on any 584 | author or copyright holder as a result of your choosing to follow a 585 | later version. 586 | 587 | 15. Disclaimer of Warranty. 588 | 589 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 590 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 591 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 592 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 593 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 594 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 595 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 596 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 597 | 598 | 16. Limitation of Liability. 599 | 600 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 601 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 602 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 603 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 604 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 605 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 606 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 607 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 608 | SUCH DAMAGES. 609 | 610 | 17. Interpretation of Sections 15 and 16. 611 | 612 | If the disclaimer of warranty and limitation of liability provided 613 | above cannot be given local legal effect according to their terms, 614 | reviewing courts shall apply local law that most closely approximates 615 | an absolute waiver of all civil liability in connection with the 616 | Program, unless a warranty or assumption of liability accompanies a 617 | copy of the Program in return for a fee. 618 | 619 | END OF TERMS AND CONDITIONS 620 | 621 | How to Apply These Terms to Your New Programs 622 | 623 | If you develop a new program, and you want it to be of the greatest 624 | possible use to the public, the best way to achieve this is to make it 625 | free software which everyone can redistribute and change under these terms. 626 | 627 | To do so, attach the following notices to the program. It is safest 628 | to attach them to the start of each source file to most effectively 629 | state the exclusion of warranty; and each file should have at least 630 | the "copyright" line and a pointer to where the full notice is found. 631 | 632 | 633 | Copyright (C) 634 | 635 | This program is free software: you can redistribute it and/or modify 636 | it under the terms of the GNU Affero General Public License as published 637 | by the Free Software Foundation, either version 3 of the License, or 638 | (at your option) any later version. 639 | 640 | This program is distributed in the hope that it will be useful, 641 | but WITHOUT ANY WARRANTY; without even the implied warranty of 642 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 643 | GNU Affero General Public License for more details. 644 | 645 | You should have received a copy of the GNU Affero General Public License 646 | along with this program. If not, see . 647 | 648 | Also add information on how to contact you by electronic and paper mail. 649 | 650 | If your software can interact with users remotely through a computer 651 | network, you should also make sure that it provides a way for users to 652 | get its source. For example, if your program is a web application, its 653 | interface could display a "Source" link that leads users to an archive 654 | of the code. There are many ways you could offer source, and different 655 | solutions will be better for different programs; see section 13 for the 656 | specific requirements. 657 | 658 | You should also get your employer (if you work as a programmer) or school, 659 | if any, to sign a "copyright disclaimer" for the program, if necessary. 660 | For more information on this, and how to apply and follow the GNU AGPL, see 661 | . 662 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | SWAGGER_CODEGEN_JAR := https://repo1.maven.org/maven2/io/swagger/swagger-codegen-cli/2.4.13/swagger-codegen-cli-2.4.13.jar 2 | BUILD_OUTPUT_DIR := swagger-build-artifacts 3 | STUB_SERVER_DIR := edx-api-stub-server 4 | 5 | help: 6 | @echo ' ' 7 | @echo 'Makefile for api-manager ' 8 | @echo ' ' 9 | @echo 'Usage: ' 10 | @echo ' make clean Delete generated python byte code and testing remnants ' 11 | @echo ' make requirements Install requirements for local development ' 12 | @echo ' make quality Run PEP8 and Pylint ' 13 | @echo ' make build Flatten the swagger docs ' 14 | @echo ' make test Run all tests ' 15 | @echo ' ' 16 | 17 | clean: 18 | find . -name '*.pyc' -delete 19 | find . -name '__pycache__' -type d -delete 20 | rm -rf $(BUILD_OUTPUT_DIR) 21 | rm -rf $(STUB_SERVER_DIR) 22 | 23 | requirements: 24 | pip install -r requirements/pip.txt 25 | pip install -qr requirements/test.txt --exists-action w 26 | 27 | quality: 28 | pep8 --config=.pep8 scripts/aws 29 | pylint --rcfile=.pylintrc scripts/aws 30 | 31 | # Download the swagger codegen jar 32 | # TODO: verify via checksum that the file is valid. 33 | codegen.download: 34 | -curl $(SWAGGER_CODEGEN_JAR) -o swagger-codegen-cli.jar 35 | 36 | # Flatten the swagger docs into a build artifact. 37 | # Assumes java 7 is installed. 38 | build: codegen.download 39 | java -jar swagger-codegen-cli.jar generate -l swagger -i swagger/api.yaml -o $(BUILD_OUTPUT_DIR) 40 | 41 | # GoCD agents have a version of Java that is not put into the path for some reason. We need to refer to it directly to get access to it. 42 | build-gocd: codegen.download 43 | /gocd-jre/bin/java -jar swagger-codegen-cli.jar generate -l swagger -i swagger/api.yaml -o $(BUILD_OUTPUT_DIR) 44 | 45 | test_python: clean requirements 46 | cd scripts/aws && python -m pytest 47 | 48 | # Spin up a stub server and hit it with tests 49 | test_swagger: codegen.download 50 | java -jar swagger-codegen-cli.jar generate -l nodejs-server -i swagger/api.yaml -o $(STUB_SERVER_DIR) 51 | cd $(STUB_SERVER_DIR) && npm install 52 | cd $(STUB_SERVER_DIR) && NODE_ENV=development node index.js 2> /dev/null & 53 | sleep 5 54 | pyresttest --url=http://localhost:8080 --test=tests/test_all.yaml 55 | killall -9 node 56 | 57 | test: clean 58 | make quality 59 | make test_python 60 | make test_swagger 61 | 62 | # Targets in a Makefile which do not produce an output file with the same name as the target name 63 | .PHONY: help requirements clean quality test 64 | 65 | upgrade: export CUSTOM_COMPILE_COMMAND=make upgrade 66 | upgrade: ## update the requirements/*.txt files with the latest packages satisfying requirements/*.in 67 | pip install -q -r requirements/pip_tools.txt 68 | pip-compile --upgrade --allow-unsafe --rebuild -o requirements/pip.txt requirements/pip.in 69 | pip-compile --upgrade -o requirements/pip_tools.txt requirements/pip_tools.in 70 | pip install -qr requirements/pip.txt 71 | pip install -qr requirements/pip_tools.txt 72 | pip-compile --upgrade -o requirements/base.txt requirements/base.in 73 | pip-compile --upgrade -o requirements/test.txt requirements/test.in 74 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # api-manager 2 | [![Build Status](https://github.com/edx/api-manager/workflows/Python%20CI/badge.svg?branch=master)](https://github.com/edx/api-manager/actions?query=workflow%3A%22Python+CI%22) 3 | 4 | Specifications and optional lightweight service for routing clients of the Open edX REST API to various endpoints within the platform. 5 | 6 | ## About 7 | The API Manager is meant to define an independently deployable application that acts as an interface to developers building on top of Open edX REST APIs. The APIs listed in this repository are not a comprehensive list of the Open edX REST API set, just the endpoints likely to be valuable to an external API consumer. 8 | 9 | The primary objectives of this service are to: 10 | * provide learners with a richer Open edX experience by creating an ecosystem of third-party apps to enhance the platform 11 | * create a framework for any Open edX deployment to hook into their own API management infrastructure 12 | * enable upstream services to iterate independently by adhering to a “mission control” strategy of having a lightweight central system that routes to service-specific configuration and code 13 | 14 | ## Getting started 15 | It's important to note that **this repository does not contain any source code** that actually runs an API management service. It contains specifications and scripts that could be used to configure a commercial off-the-shelf API management vendor, or could just be used as a documentation source. 16 | 17 | At edx.org, we're using Amazon Web Services' [API Gateway](https://aws.amazon.com/api-gateway) to power an API management service at api.edx.org, and the scripts/specs in this repository allow us to provision AWS API Gateway for our needs. See the note about vendor extensions below if this is of interest. 18 | 19 | An example API Manager is defined by an [Open API / Swagger](https://github.com/OAI/OpenAPI-Specification) specification document at [swagger/api.yaml](swagger/api.yaml). You could point the third-party tool [swagger-codegen](https://github.com/swagger-api/swagger-codegen) at this document to generate a lightweight client SDK or stub server in many languages, or just flatten the nested references into a single Swagger document using the swagger (JSON) or swagger-yaml language options (this may be required for use by certain Swagger consumers). Read the swagger-codegen docs for more information. 20 | 21 | ```sh 22 | swagger-codegen generate -l swagger -i swagger/api.yaml 23 | ``` 24 | 25 | ## Vendor extensions 26 | 27 | ### AWS API Gateway 28 | The flattened Swagger document (see note above) should "just work" when using Amazon's `ImportRestApi` feature. Note that stage variables still need to be defined that are specific to your Open edX installation. To be clear, while you may use AWS API Gateway for your specific Open edX instance, we are intentionally isolating vendor-specific hooks to avoid any lock-ins. 29 | 30 | ### Other vendor extensions 31 | None yet. 32 | 33 | ## Capabilities 34 | Below are a set of capabilities that we believe are essential when selecting an API Management vendor (or building your own). 35 | 36 | ### Routing 37 | > Contain all possible API actions within a single, central access point, to present a unified front to API clients. 38 | 39 | One of the core capabilities of an API management service is its presentation layer. API clients should not need to know the underlying deployment details in order to call various endpoints; using an example, if endpoint A is part of edx-platform, while endpoint B belongs to a separate IDA, API clients of A and B shouldn’t have to know that level of implementation detail. 40 | 41 | The simplest version of API routing, which is where we've started, is just passing requests through to an underlying origin based on calling to an “upstream” DNS entry. The API service acts as an abstraction layer. More complex routers may include service discovery mechanisms for dynamic request forwarding, but we have no plans on implementing that at this time. 42 | 43 | ### Audit logging 44 | > Keep track of all calls made against APIs for auditing, monitoring and debugging. 45 | 46 | The service should have the ability to record some/all calls made against it. Ideally, these logs can be shipped to a log analysis system in near-real-time so that we can detect API error conditions, monitor request volumes, and understand usage patterns. Here at edx.org, we're using Amazon API Gateway's built-in logging capabilities for now. 47 | 48 | ### Specification 49 | > Clearly define the API contract in a machine-parseable format so that API clients don’t need to guess about our endpoints. 50 | 51 | There are several emerging specification formats for APIs; for now, we’re using Swagger as it has wide adoption and good tooling. With well-placed Swagger documents, clients can easily interact with our APIs as well as generate client SDKs for faster adoption. 52 | Another benefit of a machine-parseable specification is that it can actually be used to configure the API management layer, in the spirit of infrastructure-as-code. This methodology is hugely beneficial at scale, and helps prevent drift between the code and the docs (a real problem for us today). These specifications are also allowed to contain vendor specific overrides (such as AWS “stage variables”). 53 | 54 | If done properly, the index file represents a readily available and complete snapshot of the API management layer with environment-level customization. The per-repo specs also enable decoupling of individual service teams from the central API management authority, which should help foster autonomy among those teams and increase velocity / decrease handoffs when changes are needed. 55 | 56 | _Note: we made a conscious decision to hand-write the per-repo specifications and index file instead of using tools like django-rest-framework-swagger that can automatically generate specs based on code introspection. These tools may be useful for unit testing an upstream service, but contain far too much internal detail and are not suitable for use by our third-party API clients. If these specifications are intended to define a contract between client and server, then we should consider any auto-generated specs to be the contract between the upstream service and the API manager; meanwhile, we should consider the hand-written specs to be the contract between the API manager and its third-party clients._ 57 | 58 | ### Authentication 59 | > Manage identity information (both application and user). 60 | 61 | The general idea is that clients interact with platform APIs using cryptographically-secured tokens that contain identity information. In Open edX, API tokens are generated using the OAuth2 protocol, where each client application has a unique “client secret” that it uses to request new tokens for that application’s users. 62 | 63 | We're increasingly using JSON Web Tokens (JWTs) as the format for API tokens. These are generated and signed by the Open edX authentication service and contain basic user information. The API management layer simply needs to verify that the token is legitimate using a public signatory key (or just forward the opaque key to the underlying service to deal with). The key advantage with JWTs is the ability to validate tokens at the API layer instead of needing to reach back to the authentication service, but that’s only valuable if we hit a ceiling on those server-side calls (which should be relatively cacheable). 64 | 65 | ### Throttling 66 | > Protect upstream services from unnecessarily heavy and expensive client load. 67 | 68 | You should consider utilizing any rate limiting / throttling features of the technology selected if available, and plan on enabling this early as it’s much harder to enforce throttling later. 69 | 70 | ### Developer support 71 | > Give API developers - this service's key user base - a clear understanding of the endpoints available and how to extract maximum value from them. 72 | 73 | There are multiple components to developer support, with varying degrees of usefulness and urgency: 74 | - Documentation (initially, can be static; ideally, dynamic based on actual specs) 75 | - Registration (profile, self-service API key requests and generation) 76 | - Support (help tickets, forums, etc) 77 | - Tools (libraries/SDKs, sandboxes) 78 | - Community evangelism (developer conferences and branded hoodies) 79 | 80 | Initially, the most critical feature is clear, updated, documentation, so that’s where we have focused our efforts. We're also working on a self-service portal for managing API keys (with a manual approval workflow). The rest of the list above are just suggestions. 81 | 82 | ### Authorization 83 | > Determine which actions an API client (application) is allowed to access, and the allowed frequency. 84 | 85 | Note that API authorization is fundamentally different from user authorization, which we currently enforce at the individual service level. Taking the example of a service for managing and querying a catalog, the division of responsibilities would be: the API Manager will determine if an application is allowed to get any Catalog information or not; the Discovery service will then need to determine if the requesting user is allowed to get information on a specific catalog. 86 | 87 | The eventual Open edX plan is to map scopes to routes, and include scope information in the user’s access token. It is not yet clear how we will manage scopes. 88 | 89 | ### Global deployment and caching 90 | > Be resilient to regional failures, and minimize client latency to the API manager. 91 | 92 | The API manager service should be globally deployable and can be opinionated about how it routes requests upstream to avoid global cross-chatter. One approach is to deploy regional management “service clusters” that each point to their region’s upstream services, and then use geographic load-balancing at the DNS layer to route client traffic to the appropriate manager. Of course, we could go the opposite direction and deploy a single logical management cluster that routes to global upstream paths, which is less maintenance work but also less efficient operationally. 93 | 94 | Another related performance improvement is API-level caching. Most API management services provide per-region caching. 95 | 96 | ## Contributing 97 | As with other Open edX codebases, please take a look at [our Contributing docs](https://github.com/edx/edx-platform/blob/master/CONTRIBUTING.rst) if you'd like to help build out this service. 98 | -------------------------------------------------------------------------------- /docs/decisions/0001-API-strategy-and-change-management-process.rst: -------------------------------------------------------------------------------- 1 | API Strategy and Change Management Process 2 | ============================================= 3 | 4 | Status 5 | ------ 6 | 7 | Draft 8 | 9 | 10 | Context 11 | ------- 12 | 13 | As enterprise APIs evolve, we need to ensure that changes are introduced in a backward-compatible manner that doesn't break existing clients, and that we have a clear and consistent process for handling these changes. 14 | 15 | Solution Approach 16 | ----------------- 17 | 18 | By adopting an API change management process, we can ensure that our API evolves in a controlled and predictable manner. This approach will ensure minimal disruptions and provide a clear approach on how to handle upstream changes to Enterprise APIs. The API change management process includes the following components: 19 | 20 | - Guidelines around API versioning 21 | - Guidelines around dealing with breaking changes 22 | - Communicating upstream changes internally and externally 23 | 24 | 25 | Decision 26 | -------- 27 | 28 | **API Versioning** 29 | 30 | - Currently, we use URI versioning in all external and internal APIs. We will continue to use this approach as it's simple and doesn't require a lot of customization on client's end. Begin with version (v1) when the API is initially released. 31 | - A new API version should only be introduced if the change is not backwards-compatible. Changes such as modifying request/response formats, removing fields, altering endpoints, or changing authentication methods are some scenarios where releasing a new version will make sense. 32 | 33 | **Guidelines around how to deal with breaking changes** 34 | 35 | - Breaking changes should be avoided whenever possible. 36 | - Breaking changes should be brought to Solution Review (Enterprise) with representation from Iris team. 37 | - If a breaking change is necessary, it should be introduced in a new version of the API, and the old version should be deprecated. 38 | - Deprecated versions of the API should be maintained for a reasonable period of time (e:g 6-12 months depending on the impact) to allow clients to migrate to the new version. 39 | - After the deprecation period, we should discontinue the support of the older version from production. 40 | 41 | **Communicate upstream changes internally and externally** 42 | 43 | - To communicate the impact of upstream changes within enterprise teams: 44 | - Request feedback from Team Iris on all relevant API changes including key stakeholders as reviewers (technical lead and product manager). 45 | - We can also create a Slack channel #enterprise-api-updates for better tracking, and to discuss any upcoming change, the rationale behind it, classify as breaking or non-breaking, and its impact. 46 | - For major changes, communicate to Iris before deployment so they can prepare for next steps (updating docs and informing clients if required). Rigorously test the changes. 47 | 48 | - To communicate the impact to clients and enterprise customers: 49 | - Clients should be notified beforehand about the deprecation plans and their timelines through documentation and through other appropriate channels. 50 | - Docs should clearly reflect all changes to the APIs (breaking and non-breaking). 51 | - In case of a version update, document all breaking changes in detail, including migration guides to assist clients in updating their integrations. 52 | - Iris will maintain an API changelog for all external APIs, specifically those with more than ~5 clients. This changelog will be available in the Developer Documentation, which is currently being developed by Team Iris. 53 | - API changelog will include a timeline of monthly updates to all the relevant APIs that have undergone any changes. 54 | 55 | 56 | Consequences 57 | ------------ 58 | 59 | - Overhead: Maintaining multiple versions of the API can increase the maintenance burden of the API. 60 | 61 | Alternatives considered 62 | ----------------------- 63 | - **Semantic Versioning:** 64 | Although this standardized approach is widely used in the industry to track breaking, major, and minor changes, it will become challenging to manage the versions of all APIs as we scale up. -------------------------------------------------------------------------------- /openedx.yaml: -------------------------------------------------------------------------------- 1 | oeps: 2 | oep-7: false 3 | oep-18: true 4 | 5 | tags: 6 | - webservice 7 | -------------------------------------------------------------------------------- /requirements/base.in: -------------------------------------------------------------------------------- 1 | -c constraints.txt 2 | 3 | boto3 4 | botocore 5 | jmespath 6 | six 7 | Jinja2 8 | google-compute-engine # not strictly required, see: https://github.com/GoogleCloudPlatform/compute-image-packages/issues/262 9 | -------------------------------------------------------------------------------- /requirements/base.txt: -------------------------------------------------------------------------------- 1 | # 2 | # This file is autogenerated by pip-compile with Python 3.11 3 | # by the following command: 4 | # 5 | # make upgrade 6 | # 7 | boto==2.49.0 8 | # via google-compute-engine 9 | boto3==1.37.25 10 | # via -r requirements/base.in 11 | botocore==1.37.25 12 | # via 13 | # -r requirements/base.in 14 | # boto3 15 | # s3transfer 16 | distro==1.9.0 17 | # via google-compute-engine 18 | google-compute-engine==2.8.13 19 | # via -r requirements/base.in 20 | jinja2==3.1.6 21 | # via -r requirements/base.in 22 | jmespath==1.0.1 23 | # via 24 | # -r requirements/base.in 25 | # boto3 26 | # botocore 27 | markupsafe==3.0.2 28 | # via jinja2 29 | python-dateutil==2.9.0.post0 30 | # via botocore 31 | s3transfer==0.11.4 32 | # via boto3 33 | six==1.17.0 34 | # via 35 | # -r requirements/base.in 36 | # python-dateutil 37 | urllib3==2.2.3 38 | # via 39 | # -c https://raw.githubusercontent.com/edx/edx-lint/master/edx_lint/files/common_constraints.txt 40 | # botocore 41 | 42 | # The following packages are considered to be unsafe in a requirements file: 43 | # setuptools 44 | -------------------------------------------------------------------------------- /requirements/constraints.txt: -------------------------------------------------------------------------------- 1 | # Version constraints for pip-installation. 2 | # 3 | # This file doesn't install any packages. It specifies version constraints 4 | # that will be applied if a package is needed. 5 | # 6 | # When pinning something here, please provide an explanation of why. Ideally, 7 | # link to other information that will help people in the future to remove the 8 | # pin when possible. Writing an issue against the offending project and 9 | # linking to it here is good. 10 | 11 | # This file contains all common constraints for edx-repos 12 | -c https://raw.githubusercontent.com/edx/edx-lint/master/edx_lint/files/common_constraints.txt 13 | -------------------------------------------------------------------------------- /requirements/pip-tools.in: -------------------------------------------------------------------------------- 1 | # Dependencies to run compile tools 2 | -c constraints.txt 3 | 4 | pip-tools # Contains pip-compile, used to generate pip requirements files -------------------------------------------------------------------------------- /requirements/pip-tools.txt: -------------------------------------------------------------------------------- 1 | # 2 | # This file is autogenerated by pip-compile with Python 3.11 3 | # by the following command: 4 | # 5 | # make upgrade 6 | # 7 | build==1.2.1 8 | # via pip-tools 9 | click==8.1.3 10 | # via pip-tools 11 | packaging==24.1 12 | # via build 13 | pip-tools==6.8.0 14 | # via -r requirements/pip-tools.in 15 | pyproject-hooks==1.1.0 16 | # via build 17 | wheel==0.37.1 18 | # via pip-tools 19 | 20 | # The following packages are considered to be unsafe in a requirements file: 21 | # pip 22 | # setuptools 23 | -------------------------------------------------------------------------------- /requirements/pip.in: -------------------------------------------------------------------------------- 1 | # Core dependencies for installing other packages 2 | -c constraints.txt 3 | 4 | pip 5 | setuptools 6 | wheel 7 | -------------------------------------------------------------------------------- /requirements/pip.txt: -------------------------------------------------------------------------------- 1 | # 2 | # This file is autogenerated by pip-compile with Python 3.11 3 | # by the following command: 4 | # 5 | # make upgrade 6 | # 7 | wheel==0.45.1 8 | # via -r requirements/pip.in 9 | 10 | # The following packages are considered to be unsafe in a requirements file: 11 | pip==24.2 12 | # via 13 | # -c https://raw.githubusercontent.com/edx/edx-lint/master/edx_lint/files/common_constraints.txt 14 | # -r requirements/pip.in 15 | setuptools==78.1.0 16 | # via -r requirements/pip.in 17 | -------------------------------------------------------------------------------- /requirements/pip_tools.in: -------------------------------------------------------------------------------- 1 | # Dependencies to run compile tools 2 | -c constraints.txt 3 | 4 | pip-tools # Contains pip-compile, used to generate pip requirements files -------------------------------------------------------------------------------- /requirements/pip_tools.txt: -------------------------------------------------------------------------------- 1 | # 2 | # This file is autogenerated by pip-compile with Python 3.11 3 | # by the following command: 4 | # 5 | # make upgrade 6 | # 7 | build==1.2.2.post1 8 | # via pip-tools 9 | click==8.1.8 10 | # via pip-tools 11 | packaging==24.2 12 | # via build 13 | pip-tools==7.4.1 14 | # via -r requirements/pip_tools.in 15 | pyproject-hooks==1.2.0 16 | # via 17 | # build 18 | # pip-tools 19 | wheel==0.45.1 20 | # via pip-tools 21 | 22 | # The following packages are considered to be unsafe in a requirements file: 23 | # pip 24 | # setuptools 25 | -------------------------------------------------------------------------------- /requirements/test.in: -------------------------------------------------------------------------------- 1 | # Requirements for running tests 2 | -c constraints.txt 3 | 4 | -r base.txt 5 | 6 | moto[cloudformation] 7 | mock 8 | pep8 9 | pylint 10 | pyresttest 11 | pytest 12 | -------------------------------------------------------------------------------- /requirements/test.txt: -------------------------------------------------------------------------------- 1 | # 2 | # This file is autogenerated by pip-compile with Python 3.11 3 | # by the following command: 4 | # 5 | # make upgrade 6 | # 7 | annotated-types==0.7.0 8 | # via pydantic 9 | astroid==3.3.9 10 | # via pylint 11 | attrs==25.3.0 12 | # via 13 | # jsonschema 14 | # referencing 15 | aws-sam-translator==1.95.0 16 | # via cfn-lint 17 | aws-xray-sdk==2.14.0 18 | # via moto 19 | boto==2.49.0 20 | # via 21 | # -r requirements/base.txt 22 | # google-compute-engine 23 | boto3==1.37.25 24 | # via 25 | # -r requirements/base.txt 26 | # aws-sam-translator 27 | # moto 28 | botocore==1.37.25 29 | # via 30 | # -r requirements/base.txt 31 | # aws-xray-sdk 32 | # boto3 33 | # moto 34 | # s3transfer 35 | certifi==2025.1.31 36 | # via requests 37 | cffi==1.17.1 38 | # via cryptography 39 | cfn-lint==1.32.1 40 | # via moto 41 | charset-normalizer==3.4.1 42 | # via requests 43 | cryptography==44.0.2 44 | # via 45 | # joserfc 46 | # moto 47 | dill==0.3.9 48 | # via pylint 49 | distro==1.9.0 50 | # via 51 | # -r requirements/base.txt 52 | # google-compute-engine 53 | docker==7.1.0 54 | # via moto 55 | future==1.0.0 56 | # via pyresttest 57 | google-compute-engine==2.8.13 58 | # via -r requirements/base.txt 59 | graphql-core==3.2.6 60 | # via moto 61 | idna==3.10 62 | # via requests 63 | iniconfig==2.1.0 64 | # via pytest 65 | isort==6.0.1 66 | # via pylint 67 | jinja2==3.1.6 68 | # via 69 | # -r requirements/base.txt 70 | # moto 71 | jmespath==1.0.1 72 | # via 73 | # -r requirements/base.txt 74 | # boto3 75 | # botocore 76 | joserfc==1.0.4 77 | # via moto 78 | jsonpatch==1.33 79 | # via cfn-lint 80 | jsonpointer==3.0.0 81 | # via jsonpatch 82 | jsonschema==4.23.0 83 | # via 84 | # aws-sam-translator 85 | # openapi-schema-validator 86 | # openapi-spec-validator 87 | jsonschema-path==0.3.4 88 | # via openapi-spec-validator 89 | jsonschema-specifications==2024.10.1 90 | # via 91 | # jsonschema 92 | # openapi-schema-validator 93 | lazy-object-proxy==1.10.0 94 | # via openapi-spec-validator 95 | markupsafe==3.0.2 96 | # via 97 | # -r requirements/base.txt 98 | # jinja2 99 | # werkzeug 100 | mccabe==0.7.0 101 | # via pylint 102 | mock==5.2.0 103 | # via -r requirements/test.in 104 | moto[cloudformation]==5.1.2 105 | # via -r requirements/test.in 106 | mpmath==1.3.0 107 | # via sympy 108 | networkx==3.4.2 109 | # via cfn-lint 110 | openapi-schema-validator==0.6.3 111 | # via openapi-spec-validator 112 | openapi-spec-validator==0.7.1 113 | # via moto 114 | packaging==24.2 115 | # via pytest 116 | pathable==0.4.4 117 | # via jsonschema-path 118 | pep8==1.7.1 119 | # via -r requirements/test.in 120 | platformdirs==4.3.7 121 | # via pylint 122 | pluggy==1.5.0 123 | # via pytest 124 | py-partiql-parser==0.6.1 125 | # via moto 126 | pycparser==2.22 127 | # via cffi 128 | pycurl==7.45.6 129 | # via pyresttest 130 | pydantic==2.11.1 131 | # via aws-sam-translator 132 | pydantic-core==2.33.0 133 | # via pydantic 134 | pylint==3.3.6 135 | # via -r requirements/test.in 136 | pyparsing==3.2.3 137 | # via moto 138 | pyresttest==1.7.1 139 | # via -r requirements/test.in 140 | pytest==8.3.5 141 | # via -r requirements/test.in 142 | python-dateutil==2.9.0.post0 143 | # via 144 | # -r requirements/base.txt 145 | # botocore 146 | # moto 147 | pyyaml==6.0.2 148 | # via 149 | # cfn-lint 150 | # jsonschema-path 151 | # moto 152 | # pyresttest 153 | # responses 154 | referencing==0.36.2 155 | # via 156 | # jsonschema 157 | # jsonschema-path 158 | # jsonschema-specifications 159 | regex==2024.11.6 160 | # via cfn-lint 161 | requests==2.32.3 162 | # via 163 | # docker 164 | # jsonschema-path 165 | # moto 166 | # responses 167 | responses==0.25.7 168 | # via moto 169 | rfc3339-validator==0.1.4 170 | # via openapi-schema-validator 171 | rpds-py==0.24.0 172 | # via 173 | # jsonschema 174 | # referencing 175 | s3transfer==0.11.4 176 | # via 177 | # -r requirements/base.txt 178 | # boto3 179 | six==1.17.0 180 | # via 181 | # -r requirements/base.txt 182 | # python-dateutil 183 | # rfc3339-validator 184 | sympy==1.13.3 185 | # via cfn-lint 186 | tomlkit==0.13.2 187 | # via pylint 188 | typing-extensions==4.13.0 189 | # via 190 | # aws-sam-translator 191 | # cfn-lint 192 | # pydantic 193 | # pydantic-core 194 | # referencing 195 | # typing-inspection 196 | typing-inspection==0.4.0 197 | # via pydantic 198 | urllib3==2.2.3 199 | # via 200 | # -c https://raw.githubusercontent.com/edx/edx-lint/master/edx_lint/files/common_constraints.txt 201 | # -r requirements/base.txt 202 | # botocore 203 | # docker 204 | # requests 205 | # responses 206 | werkzeug==3.1.3 207 | # via moto 208 | wrapt==1.17.2 209 | # via aws-xray-sdk 210 | xmltodict==0.14.2 211 | # via moto 212 | 213 | # The following packages are considered to be unsafe in a requirements file: 214 | # setuptools 215 | -------------------------------------------------------------------------------- /scripts/__init__.py: -------------------------------------------------------------------------------- 1 | # intentionally empty 2 | -------------------------------------------------------------------------------- /scripts/aws/README.md: -------------------------------------------------------------------------------- 1 | ## scripts/aws 2 | The `api-manager` Swagger documents in this repository contain some vendor-specific deployment hooks. This directory contains a few scripts that help with deploying your very own api-manager to Amazon Web Services' API Gateway service. 3 | 4 | You *do not* need to deploy an API Manager in your Open edX installation, and you *do not* need to use Amazon here. But if you choose to go this route, and want to use Amazon's gateway service, feel free to use these tools to get started. 5 | 6 | ### Setup 7 | See the requirements.txt file for more information on the various Python dependencies needed. Just run `pip install -r requirements.txt` in this directory to get started. Right now, only `botocore` is necessary beyond the stock Python packages. 8 | 9 | ### Design 10 | Before getting started here, please familiarize yourself with [Amazon API Gateway](https://aws.amazon.com/api-gateway/). 11 | 12 | The approach these scripts take to deployment is not standard (we're not sure there _is_ a standard) and may not fit your exact use case. Where possible, we will call out API Gateway specific objects as `aws.apigateway.X` below. 13 | 14 | The flow is as follows: 15 | 16 | 1. *Pre-work*: we expect that each API lives behind a custom domain (`aws.apigateway.DomainName`) that has already been provisioned - see [the AWS docs](http://docs.aws.amazon.com/apigateway/latest/developerguide/how-to-custom-domains.html) for more detail. 17 | 18 | 2. *Bootstrapping*: the [bootstrap](bootstrap.py) script creates a new `aws.apigateway.RestApi` object and deploys it to a "bootstrap" `aws.apigateway.Stage` with a simple hello-world API defined by [bootstrap.json](bootstrap.json). 19 | 20 | 3. *Build*: clone this repo and point [swagger-codegen](https://github.com/swagger-api/swagger-codegen) at the top-level `api.yaml` file to generate a "flattened" Swagger JSON document (hint: use `-l swagger`). 21 | 22 | 4. *Deployment*: the [deploy](deploy.py) script takes the flattened Swagger document and uploads it to the `aws.apigateway.RestApi` in a new stage, following a simple "ring" approach. (Given an ordered list of stages, the script will figure out which stage is live and automatically push to the next stage in the sequence.) 23 | 24 | 5. *Activation*: the [flip](flip.py) script updates the `aws.apigateway.DomainName` to point to the newly deployed stage - or, more specifically, whatever stage you want. You can also use this script to quickly roll back your API to a previous stage in the ring. 25 | 26 | ### Environment 27 | Make sure `AWS_REGION`, `AWS_ACCESS_KEY_ID` and `AWS_SECRET_ACCESS_KEY` are set up as per [AWS' instructions](http://boto3.readthedocs.org/en/latest/guide/configuration.html#environment-variables). 28 | -------------------------------------------------------------------------------- /scripts/aws/__init__.py: -------------------------------------------------------------------------------- 1 | # intentionally empty 2 | -------------------------------------------------------------------------------- /scripts/aws/bootstrap.json: -------------------------------------------------------------------------------- 1 | { 2 | "swagger": "2.0", 3 | "info": { 4 | "version": "0.0.0", 5 | "title": "bootstrap" 6 | }, 7 | "host": "api.example.org", 8 | "basePath": "/", 9 | "schemes": [ 10 | "https" 11 | ], 12 | "paths": { 13 | "/": { 14 | "get": { 15 | "consumes": [ 16 | "application/json" 17 | ], 18 | "produces": [ 19 | "application/json" 20 | ], 21 | "responses": { 22 | "200": { 23 | "description": "OK" 24 | } 25 | }, 26 | "x-amazon-apigateway-integration": { 27 | "responses": { 28 | "default": { 29 | "statusCode": "200", 30 | "responseTemplates": { 31 | "application/json": "{\"hello\": \"world\"}" 32 | } 33 | } 34 | }, 35 | "requestTemplates": { 36 | "application/json": "{\"statusCode\": 200}" 37 | }, 38 | "type": "mock" 39 | } 40 | } 41 | } 42 | } 43 | } -------------------------------------------------------------------------------- /scripts/aws/bootstrap.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | 3 | """Various functions to bootstrap new AWS API Gateway instances.""" 4 | 5 | import os 6 | import logging 7 | import argparse 8 | import boto3 9 | import botocore.exceptions 10 | 11 | 12 | CLOUDFRONT_HOSTED_ZONE = "Z2FDTNDATAQYW2" 13 | 14 | 15 | def get_domain(api_base): 16 | """Returns a dictionary response for the specified domain or None if the domain does not exit""" 17 | client = boto3.client('apigateway', region_name=args.aws_region) # pylint: disable=possibly-used-before-assignment 18 | 19 | try: 20 | response = client.get_domain_name(domainName=api_base) 21 | except botocore.exceptions.ClientError: 22 | return None 23 | 24 | return response 25 | 26 | 27 | def get_base_path(api_base): 28 | """Returns a dictionary response for the specified base path or None if the base path does not exist""" 29 | 30 | client = boto3.client('apigateway', region_name=args.aws_region) 31 | 32 | try: 33 | mapping = client.get_base_path_mapping( 34 | domainName=api_base, 35 | basePath='(none)') 36 | except botocore.exceptions.ClientError: 37 | return None 38 | 39 | return mapping 40 | 41 | 42 | def create_apigw_custom_domain_name(domain_name, cert_name, cert_body, cert_pk, cert_chain): 43 | """Creates an api gateway custom domain entity""" 44 | 45 | client = boto3.client('apigateway', region_name=args.aws_region) 46 | 47 | try: 48 | response = client.create_domain_name( 49 | domainName=domain_name, 50 | certificateName=cert_name, 51 | certificateBody=cert_body, 52 | certificatePrivateKey=cert_pk, 53 | certificateChain=cert_chain 54 | ) 55 | except Exception as e: 56 | raise e 57 | 58 | return response 59 | 60 | 61 | def create_route53_rs(host_zone, domain_name, alias_target): 62 | """Creates a A record Alias pointing to the hostname of the api gateways internal cloudfront distribution""" 63 | client = boto3.client('route53', region_name=args.aws_region) 64 | 65 | changes = {"Changes": [{ 66 | "Action": "UPSERT", 67 | "ResourceRecordSet": { 68 | "Name": domain_name + ".", 69 | "Type": "A", 70 | "AliasTarget": { 71 | "HostedZoneId": CLOUDFRONT_HOSTED_ZONE, 72 | "DNSName": alias_target + ".", 73 | "EvaluateTargetHealth": False 74 | } 75 | } 76 | }]} 77 | 78 | client.change_resource_record_sets(HostedZoneId=host_zone, ChangeBatch=changes) 79 | 80 | 81 | def bootstrap_api(stage_name): 82 | """ 83 | Upload a bootstrap Swagger document to a new API Gateway object and set it live 84 | with environment-specific variables. 85 | """ 86 | 87 | client = boto3.client('apigateway', region_name=args.aws_region) 88 | 89 | # bootstrap.json is relative to me; where am I? 90 | my_dir = os.path.dirname(os.path.realpath(__file__)) 91 | 92 | bootstrap_swagger = open(my_dir + '/bootstrap.json', 'r', encoding='utf-8') # pylint: disable=consider-using-with 93 | 94 | response = client.import_rest_api(body=bootstrap_swagger.read()) 95 | logging.info('New bootstrap API ID "%s" created', response['id']) 96 | 97 | client.create_deployment( 98 | restApiId=response['id'], 99 | stageName=stage_name) 100 | logging.info('API ID "%s" deployed to stage "%s"', response['id'], stage_name) 101 | 102 | return response['id'] 103 | 104 | 105 | def create_base_path_mapping(rest_api_id, api_base, stage_name): 106 | """Link a custom domain with an API Gateway object stage""" 107 | 108 | client = boto3.client('apigateway', region_name=args.aws_region) 109 | 110 | # Note: this will fail if a mapping already exists (bootstrapping is not idempotent). 111 | response = client.create_base_path_mapping( 112 | domainName=api_base, 113 | basePath='(none)', 114 | restApiId=rest_api_id, 115 | stage=stage_name 116 | ) 117 | logging.info("Domain '%s' now pointed to '%s':'%s'", api_base, rest_api_id, stage_name) 118 | return response 119 | 120 | 121 | def file_arg_to_string(filename): 122 | """Returns file content as string""" 123 | with open(filename, "r", encoding='utf-8') as fin: 124 | body = fin.read() 125 | 126 | return body 127 | 128 | 129 | if __name__ == '__main__': 130 | 131 | logging.basicConfig(level=logging.INFO, format='[%(asctime)s] %(levelname)s %(message)s') 132 | 133 | parser = argparse.ArgumentParser() 134 | 135 | parser.add_argument("--aws-profile", required=True) 136 | parser.add_argument("--aws-region", default="us-east-1") 137 | parser.add_argument("--stage-name", default="bootstrap") 138 | parser.add_argument("--api-base-domain", required=True, 139 | help="The name of the API Gateway domain to be created.") 140 | parser.add_argument("--ssl-cert-name", required=True, 141 | help="The name of the SSL certificate to associate with the daomin.") 142 | parser.add_argument("--ssl-cert", required=True, 143 | help="The path to the file containing the SSL cert from the CA.") 144 | parser.add_argument("--ssl-pk", required=True, 145 | help="The Private Key created when generating the CSR for the SSL certificte.") 146 | parser.add_argument("--ssl-cert-chain", required=True, 147 | help="The certificate chain provided by the CA.") 148 | parser.add_argument("--route53-hosted-zone", required=True, 149 | help="The AWS ID of the the Route53 hosted zone used for managing gateway DNS.") 150 | 151 | args = parser.parse_args() 152 | 153 | # Configure the default session and prompt for MFA token 154 | if args.aws_profile: 155 | boto3.setup_default_session(profile_name=args.aws_profile) 156 | 157 | # read file arguments into string vars 158 | ssl_cert = file_arg_to_string(args.ssl_cert) 159 | ssl_pk = file_arg_to_string(args.ssl_pk) 160 | ssl_cert_chain = file_arg_to_string(args.ssl_cert_chain) 161 | 162 | # Phase 1, create the api gateway "custom domain" and associated DNS record. 163 | 164 | # Note: 165 | # It can take up to 40 minutes for creation to complate. 166 | # Deletion takes time in the background, re-use of names, even for apparently 167 | # deleted domains can be problematic. 168 | domain = get_domain(args.api_base_domain) 169 | 170 | if not domain: 171 | logging.info("Custom domain does not exist, creating") 172 | domain = create_apigw_custom_domain_name(args.api_base_domain, args.ssl_cert_name, 173 | ssl_cert, ssl_pk, ssl_cert_chain) 174 | 175 | logging.info("Upserting DNS for the custom domain.") 176 | create_route53_rs(args.route53_hosted_zone, args.api_base_domain, domain['distributionDomainName']) 177 | 178 | # Phase 2, create the api gateway and dummy base path mapping 179 | 180 | base_path = get_base_path(args.api_base_domain) 181 | 182 | if not base_path: 183 | 184 | # Create new dummy API Gateway object and deploy to a stage 185 | api_id = bootstrap_api(args.stage_name) 186 | 187 | # Link custom domain to stage (base path mapping) 188 | create_base_path_mapping(api_id, args.api_base_domain, args.stage_name) 189 | 190 | logging.info('Bootstrap successful.') 191 | 192 | else: 193 | api_id = base_path['restApiId'] 194 | logging.info('Bootstrap not necessary.') 195 | 196 | logging.info('Completed bootstrapping for API "%s".', api_id) 197 | -------------------------------------------------------------------------------- /scripts/aws/common/__init__.py: -------------------------------------------------------------------------------- 1 | # intentionally empty 2 | -------------------------------------------------------------------------------- /scripts/aws/common/deploy.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | 3 | """Various functions for day-to-day management of AWS API Gateway instances.""" 4 | 5 | import logging 6 | import botocore.session 7 | import botocore.exceptions 8 | 9 | 10 | def get_api_id(client, api_base_domain): 11 | """Get the current live API ID and stage tied to this base path.""" 12 | try: 13 | response = client.get_base_path_mapping( 14 | domainName=api_base_domain, 15 | basePath='(none)') 16 | except botocore.exceptions.ClientError as exc: 17 | raise ValueError('No mapping found for "%s"' % api_base_domain) from exc # pylint: disable=consider-using-f-string 18 | 19 | logging.info('Found existing base path mapping for API ID "%s", stage "%s"', 20 | response['restApiId'], response['stage']) 21 | 22 | return (response['restApiId'], response['stage']) 23 | 24 | 25 | def get_next_stage(rotation, cur_stage): 26 | """ 27 | Based on a pre-set stage rotation order, and a pointer to the current location in the order, 28 | determine the next stage based on a simple circular iteration. If the pointer is invalid, 29 | start at the first stage. 30 | """ 31 | 32 | next_index = 0 33 | 34 | num_rotations = len(rotation) 35 | 36 | if num_rotations == 0: 37 | raise ValueError("No rotation order provided, cannot return next stage.") 38 | 39 | try: 40 | cur_index = rotation.index(cur_stage) 41 | 42 | # Circular iteration. If we're at the end, go back to the beginning! 43 | if cur_index < num_rotations - 1: 44 | next_index = cur_index + 1 45 | 46 | except ValueError: 47 | logging.info('Stage "%s" is not in the rotation, starting from the top.', cur_stage) 48 | 49 | next_stage = rotation[next_index] 50 | 51 | logging.info('Rotating from stage "%s" to "%s".', cur_stage, next_stage) 52 | return next_stage 53 | 54 | 55 | def deploy_api(client, rest_api_id, swagger_filename, stage_name, stage_variables): 56 | """ 57 | Upload the Swagger document to an existing API Gateway object and set it live 58 | with environment-specific variables. 59 | """ 60 | 61 | swagger = open(swagger_filename, 'r', encoding="utf-8") # pylint: disable=consider-using-with 62 | 63 | api_response = client.put_rest_api( 64 | restApiId=rest_api_id, 65 | mode='overwrite', 66 | body=swagger.read(), 67 | parameters={'binaryMediaTypes': 'multipart/form-data'}, # This MIME needs to be binary for file uploads 68 | ) 69 | logging.info('Existing API ID "%s" updated (name "%s")', api_response['id'], api_response['name']) 70 | 71 | deployment_response = client.create_deployment( 72 | restApiId=rest_api_id, 73 | stageName=stage_name, 74 | variables=stage_variables) 75 | 76 | logging.info('API ID "%s" deployed (deployment ID %s)', rest_api_id, deployment_response['id']) 77 | 78 | return deployment_response['id'] 79 | 80 | 81 | def update_stage(client, rest_api_id, stage_name, stage_settings): 82 | """ 83 | Modify deployed stage with throttling, logging and caching settings. 84 | Note that you can define path-level overrides if you want; we're not 85 | tackling that at this time but it's theoretically possible. 86 | """ 87 | 88 | response = client.update_stage( 89 | restApiId=rest_api_id, 90 | stageName=stage_name, 91 | patchOperations=[ 92 | {'op': 'replace', 'path': '/*/*/logging/loglevel', 'value': stage_settings['log_level']}, 93 | {'op': 'replace', 'path': '/*/*/metrics/enabled', 'value': stage_settings['metrics']}, 94 | {'op': 'replace', 'path': '/*/*/caching/enabled', 'value': stage_settings['caching']}, 95 | {'op': 'replace', 'path': '/*/*/throttling/rateLimit', 'value': stage_settings['rate_limit']}, 96 | {'op': 'replace', 'path': '/*/*/throttling/burstLimit', 'value': stage_settings['burst_limit']} 97 | ]) 98 | 99 | logging.info('API ID "%s", stage "%s" updated with settings: %s', 100 | rest_api_id, stage_name, response['methodSettings']) 101 | 102 | return response 103 | 104 | 105 | def deploy(cli_args, integration_settings, stage_settings): 106 | """Deploys an API to a new stage based on provided settings and domain.""" 107 | session = botocore.session.get_session() 108 | apig = session.create_client('apigateway', cli_args.aws_region) 109 | 110 | # Look up API ID based on the custom domain link. 111 | (api_id, current_stage) = get_api_id(apig, cli_args.api_base_domain) 112 | 113 | # Get the next stage in rotation. 114 | new_stage = get_next_stage(cli_args.rotation_order, current_stage) 115 | 116 | # Activate the API with the requested stage variables. 117 | deploy_api(apig, api_id, cli_args.swagger_filename, new_stage, integration_settings) 118 | 119 | # Apply stage setting updates. 120 | update_stage(apig, api_id, new_stage, stage_settings) 121 | 122 | # Return new stage name. 123 | print(new_stage) 124 | -------------------------------------------------------------------------------- /scripts/aws/deploy.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | 3 | """Various functions for day-to-day management of AWS API Gateway instances.""" 4 | 5 | import argparse 6 | import logging 7 | from scripts.aws.common.deploy import deploy 8 | 9 | if __name__ == '__main__': 10 | 11 | logging.basicConfig(level=logging.INFO, format='[%(asctime)s] %(levelname)s %(message)s') 12 | 13 | parser = argparse.ArgumentParser() 14 | 15 | parser.add_argument("--aws-region", required=False, default="us-east-1") 16 | parser.add_argument( 17 | "--api-base-domain", required=True, 18 | help="The name of the API Gateway domain to be created." 19 | ) 20 | parser.add_argument( 21 | "--swagger-filename", required=True, 22 | help="The name of a complete Swagger 2.0 specification file with AWS vendor hooks." 23 | ) 24 | parser.add_argument( 25 | "--tag", required=True, 26 | help="Unique identifier for this deployment (such as a git hash)" 27 | ) 28 | parser.add_argument( 29 | "--rotation-order", required=True, nargs='+', 30 | help="Ordered list of stages in the deployment ring (ex: 'red black')" 31 | ) 32 | parser.add_argument( 33 | "--log-level", required=False, default="OFF", choices=['OFF', 'ERROR', 'INFO'], 34 | help="Verbosity of messages sent to CloudWatch Logs" 35 | ) 36 | parser.add_argument( 37 | "--metrics", required=False, default="false", choices=['false', 'true'], 38 | help="Enable CloudWatch metrics" 39 | ) 40 | parser.add_argument( 41 | "--caching", required=False, default="false", choices=['false', 'true'], 42 | help="Enable API Gateway caching feature" 43 | ) 44 | parser.add_argument( 45 | "--rate-limit", required=False, default="500", type=str, 46 | help="Default per-resource average rate limit" 47 | ) 48 | parser.add_argument( 49 | "--burst-limit", required=False, default="1000", type=str, 50 | help="Default per-resource maximum rate limit" 51 | ) 52 | parser.add_argument( 53 | "--landing-page", required=True, 54 | help="Location of landing page for 'root' level requests" 55 | ) 56 | parser.add_argument( 57 | "--edxapp-host", required=True, 58 | help="Location of edxapp for request routing" 59 | ) 60 | parser.add_argument( 61 | "--catalog-host", required=True, 62 | help="Location of catalog IDA for request routing" 63 | ) 64 | parser.add_argument( 65 | "--enterprise-host", required=False, default='', 66 | help="Location of enterprise IDA for request routing" 67 | ) 68 | parser.add_argument( 69 | '--analytics-api-host', required=True, 70 | help="Location of analyitcs-api IDA for request routing" 71 | ) 72 | parser.add_argument( 73 | '--registrar-host', required=True, 74 | help="Location of registrar IDA for request routing" 75 | ) 76 | parser.add_argument( 77 | '--enterprise-catalog-host', required=True, 78 | help="Location of enterprise catalog IDA for request routing" 79 | ) 80 | parser.add_argument( 81 | '--authoring-host', required=True, 82 | help="Location of Studio for authoring request routing" 83 | ) 84 | parser.add_argument( 85 | '--license-manager-host', required=True, 86 | help="Location of License Manager IDA for request routing" 87 | ) 88 | parser.add_argument( 89 | '--enterprise-access-host', required=True, 90 | help="Location of Enterprise Access IDA for request routing" 91 | ) 92 | 93 | cli_args = parser.parse_args() 94 | integration_settings = { 95 | 'id': cli_args.tag, 96 | 'landing_page': cli_args.landing_page, 97 | 'edxapp_host': cli_args.edxapp_host, 98 | 'discovery_host': cli_args.catalog_host, 99 | 'enterprise_host': cli_args.enterprise_host or cli_args.edxapp_host, 100 | 'gateway_host': cli_args.api_base_domain, 101 | 'analytics_api_host': cli_args.analytics_api_host, 102 | 'registrar_host': cli_args.registrar_host, 103 | 'enterprise_catalog_host': cli_args.enterprise_catalog_host, 104 | 'authoring_host': cli_args.authoring_host, 105 | 'license_manager_host': cli_args.license_manager_host, 106 | 'enterprise_access_host': cli_args.enterprise_access_host 107 | } 108 | stage_settings = { 109 | 'log_level': cli_args.log_level, 110 | 'metrics': cli_args.metrics, 111 | 'caching': cli_args.caching, 112 | 'rate_limit': cli_args.rate_limit, 113 | 'burst_limit': cli_args.burst_limit 114 | } 115 | deploy(cli_args, integration_settings, stage_settings) 116 | -------------------------------------------------------------------------------- /scripts/aws/flip.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | 3 | """Various functions for day-to-day management of AWS API Gateway instances.""" 4 | 5 | import argparse 6 | import sys 7 | import logging 8 | import botocore.session 9 | import botocore.exceptions 10 | 11 | 12 | def get_live_stage(client, api_base): 13 | """Get the current live stage tied to this base path.""" 14 | try: 15 | response = client.get_base_path_mapping( 16 | domainName=api_base, 17 | basePath='(none)') 18 | except botocore.exceptions.ClientError: 19 | logging.error('No mapping found for "%s", have you bootstrapped it yet?', api_base) 20 | sys.exit(1) 21 | 22 | logging.info('Found existing base path mapping for API ID "%s", stage "%s"', 23 | response['restApiId'], response['stage']) 24 | 25 | return response['stage'] 26 | 27 | 28 | def update_base_path_mapping(client, api_base, stage_name): 29 | """Flip base path pointer to new gateway object so it starts receiving real traffic.""" 30 | 31 | try: 32 | response = client.update_base_path_mapping( 33 | domainName=api_base, 34 | basePath='(none)', 35 | patchOperations=[ 36 | {'op': 'replace', 'path': '/stage', 'value': stage_name} 37 | ]) 38 | except botocore.exceptions.ClientError: 39 | logging.error('Stage "%s" does not yet exist. Aborting operation.', stage_name) 40 | raise 41 | 42 | logging.info('API Gateway domain "%s" updated to "%s"', api_base, stage_name) 43 | return response 44 | 45 | 46 | if __name__ == '__main__': 47 | 48 | logging.basicConfig(level=logging.INFO, format='[%(asctime)s] %(levelname)s %(message)s') 49 | 50 | parser = argparse.ArgumentParser() 51 | 52 | parser.add_argument("--aws-region", required=False, default="us-east-1") 53 | parser.add_argument("--api-base-domain", required=True, 54 | help="The name of the API Gateway domain to be created.") 55 | parser.add_argument("--next-stage", required=True, 56 | help="The name of the API Gateway stage to be activated.") 57 | 58 | args = parser.parse_args() 59 | 60 | session = botocore.session.get_session() 61 | apig = session.create_client('apigateway', args.aws_region) 62 | 63 | # Make sure we aren't doing any redundant work 64 | if args.next_stage == get_live_stage(apig, args.api_base_domain): 65 | logging.info('Stage "%s" is already the live stage; nothing to do here.', args.next_stage) 66 | 67 | # Flip the base path pointer to the new stage 68 | else: 69 | update_base_path_mapping(apig, args.api_base_domain, args.next_stage) 70 | -------------------------------------------------------------------------------- /scripts/aws/monitor.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # 3 | # Pre-reqs: 4 | # Run this script from the directory its in 5 | # 6 | # Arguments: 7 | # This script requires following arguments 8 | # --api-base-domain (name of the API Gateway domain) 9 | # --splunk-host (splunk host IP and port) 10 | # --splunk-token (base-64 encoded splunk access token) 11 | # --acct-id (aws account id) 12 | # --lambda-timeout (The function execution time) 13 | # --lambda-memory (The amount of memory, in MB, your Lambda function is given) 14 | # --kms-key (The KMS key) 15 | # --subnet-list (space seperated list of subnet IDs for VPC config) 16 | # --sg-list (space seperated list of security group IDs for VPC config) 17 | # --environment (the environment where lambda function is to be created) 18 | # --deployment (the deployment for which lambda function is created) 19 | # e.g. 20 | # python monitor.py --api-base-domain test.edx.org --splunk-host 10.2.1.2:99 --splunk-token xxx \ 21 | # --acct-id 000 --lambda-timeout 10 --lambda-memory 512 --kms-key xxxx-xx-xx-xxx 22 | # --subnet-list subnet-112 subnet-113 --sg-list sg-899 sg-901 --environment stage --deployment edx 23 | # 24 | """ 25 | Api Gateway monitoring scripts 26 | """ 27 | import logging 28 | import time 29 | import argparse 30 | import tempfile 31 | import shutil 32 | from zipfile import ZipFile 33 | from os.path import os, basename 34 | import botocore.session 35 | import botocore.exceptions 36 | from jinja2 import Environment, FileSystemLoader 37 | 38 | 39 | def get_api_id(client, api_base_domain): 40 | """Get the current live API ID and stage tied to this base path.""" 41 | try: 42 | response = client.get_base_path_mapping( 43 | domainName=api_base_domain, 44 | basePath='(none)') 45 | except botocore.exceptions.ClientError as exception: 46 | raise ValueError('No mapping found for "%s"' % api_base_domain) from exception # pylint: disable=consider-using-f-string 47 | 48 | logging.info('Found existing base path mapping for API ID "%s", stage "%s"', 49 | response['restApiId'], response['stage']) 50 | 51 | return (response['restApiId'], response['stage']) 52 | 53 | 54 | def create_api_alarm(*, cw_session, alarm_name, metric, 55 | namespace, stat, comparison, description, 56 | threshold, period, eval_period, dimensions, topic): 57 | """Puts data to the metric, then creates the alarm for appropriate metric in API Gateway""" 58 | cw_session.put_metric_data( 59 | Namespace=namespace, 60 | MetricData=[{'MetricName': metric, 'Dimensions': dimensions, 'Value': 0}, ]) 61 | response = cw_session.put_metric_alarm( 62 | AlarmName=alarm_name, 63 | AlarmDescription=description, 64 | ActionsEnabled=True, 65 | Namespace=namespace, 66 | Dimensions=dimensions, 67 | MetricName=metric, 68 | Statistic=stat, 69 | Period=period, 70 | EvaluationPeriods=eval_period, 71 | Threshold=threshold, 72 | ComparisonOperator=comparison, 73 | AlarmActions=[topic]) 74 | 75 | logging.info('response for creating api alarm = "%s"', 76 | response['ResponseMetadata']) 77 | 78 | 79 | def create_lambda_function_zip(jinja_env, temp_dir, splunk_host, splunk_token, lf_name): 80 | """Updates and Zips the lambda function file""" 81 | splunk_values = { 82 | 'splunk_ip': splunk_host, 83 | 'token': splunk_token, 84 | 'lambda_function_name': lf_name, 85 | } 86 | js_file = temp_dir + '/index.js' 87 | with open(js_file, 'w', encoding='utf-8') as lambda_function_file: 88 | lf_data = jinja_env.get_template('index.js.j2').render(splunk_values) 89 | lambda_function_file.write(lf_data) 90 | 91 | zip_file = temp_dir + '/lambda.zip' 92 | with ZipFile(zip_file, 'w') as lambda_zip: 93 | lambda_zip.write(js_file, basename(js_file)) 94 | return zip_file 95 | 96 | 97 | def get_lambda_exec_policy(*, jinja_env, temp_dir, region, acct_id, func_name, kms_key): 98 | """updates the policy json and returns it""" 99 | resource_values = { 100 | 'region': region, 101 | 'acct_id': acct_id, 102 | 'func_name': func_name, 103 | 'kms_key': kms_key, 104 | } 105 | json_file = temp_dir + '/lambda_exec_policy.json' 106 | with open(json_file, 'w', encoding='utf-8') as json_policy_file: 107 | json_data = jinja_env.get_template('lambda_exec_policy.json.j2').render(resource_values) 108 | json_policy_file.write(json_data) 109 | return json_file 110 | 111 | 112 | def role_exists(iam, role_name): 113 | """Checks if the role exists already""" 114 | try: 115 | iam.get_role(RoleName=role_name) 116 | except botocore.exceptions.ClientError: 117 | return False 118 | return True 119 | 120 | 121 | def get_role_arn(iam, role_name): 122 | """Gets the ARN of role""" 123 | response = iam.get_role(RoleName=role_name) 124 | return response['Role']['Arn'] 125 | 126 | 127 | def lambda_exists(client, function_name): 128 | """Checks if the function exists already""" 129 | try: 130 | client.get_function(FunctionName=function_name) 131 | except botocore.exceptions.ClientError: 132 | return False 133 | return True 134 | 135 | 136 | def attach_managed_policy(iam, role_name, policy_arn): 137 | """Attaches a managed policy to an existing role""" 138 | response = iam.attach_role_policy(RoleName=role_name, 139 | PolicyArn=policy_arn) 140 | logging.info('response for attaching managed policy to role = "%s"', response) 141 | 142 | 143 | def create_role_with_inline_policy(iam, policy_name, assume_role_policy_document, policy_str): 144 | """Creates a new role with inline policy if there is not already a role by that name""" 145 | if role_exists(iam, policy_name): 146 | logging.info('Role "%s" already exists. Assuming correct values.', policy_name) 147 | return get_role_arn(iam, policy_name) 148 | 149 | response = iam.create_role(RoleName=policy_name, 150 | AssumeRolePolicyDocument=assume_role_policy_document) 151 | iam.put_role_policy(RoleName=policy_name, 152 | PolicyName='inlinepolicy', PolicyDocument=policy_str) 153 | logging.info('response for creating role = "%s"', response) 154 | return response['Role']['Arn'] 155 | 156 | 157 | def create_role_with_managed_policy(iam, role_name, assume_role_policy_document, policy_arn): 158 | """Creates a new role with managed policy if there is not already a role by that name""" 159 | if role_exists(iam, role_name): 160 | logging.info('Role "%s" already exists. Assuming correct values.', role_name) 161 | return get_role_arn(iam, role_name) 162 | 163 | response = iam.create_role(RoleName=role_name, 164 | AssumeRolePolicyDocument=assume_role_policy_document) 165 | attach_managed_policy(iam, role_name, policy_arn) 166 | logging.info('response for creating role = "%s"', response) 167 | return response['Role']['Arn'] 168 | 169 | 170 | def create_lambda_function(*, client, function_name, runtime, role, 171 | handler, zip_file, description, timeout, mem_size, vpc): 172 | """Creates a lambda function to pull data from cloudwatch event. 173 | It only works works in VPC""" 174 | try: 175 | code_file = open(zip_file, 'rb') # pylint: disable=consider-using-with 176 | if lambda_exists(client, function_name): 177 | logging.info('"%s" function already exists. Updating its code', function_name) 178 | response = client.update_function_code( 179 | FunctionName=function_name, 180 | ZipFile=code_file.read(), 181 | Publish=True) 182 | 183 | else: 184 | response = client.create_function( 185 | FunctionName=function_name, 186 | Runtime=runtime, 187 | Role=role, 188 | Handler=handler, 189 | Code={ 190 | 'ZipFile': code_file.read(), 191 | }, 192 | Description=description, 193 | Timeout=timeout, 194 | MemorySize=mem_size, 195 | Publish=True, 196 | VpcConfig=vpc) 197 | 198 | logging.info('response for lambda function = "%s"', 199 | response) 200 | except IOError: 201 | logging.error('Unable to open the zip file') 202 | finally: 203 | code_file.close() 204 | 205 | 206 | def get_topic_arn(client, topic_name): 207 | """Gets the Arn of an SNS topic""" 208 | response = client.list_topics() 209 | for value in response['Topics']: 210 | sns_arn = value['TopicArn'] 211 | if topic_name in str(sns_arn): 212 | return str(sns_arn) 213 | return None 214 | 215 | 216 | def get_api_gateway_name(client, gw_id): 217 | """gets the name of the API Gateway""" 218 | gw_res = client.get_rest_apis() 219 | for value in gw_res['items']: 220 | if value['id'] == gw_id: 221 | gw_name = value['name'] 222 | return str(gw_name) 223 | return None 224 | 225 | 226 | def add_cloudwatchlog_role_to_apigateway(client, role_arn): 227 | """updates the role ARN to allow api gateway to push logs to cloudwatch""" 228 | response = client.update_account( 229 | patchOperations=[{'op': 'replace', 'path': '/cloudwatchRoleArn', 'value': role_arn}, ]) 230 | logging.info('response for updating role = "%s"', response) 231 | 232 | 233 | if __name__ == '__main__': 234 | 235 | logging.basicConfig(level=logging.INFO, format='[%(asctime)s] %(levelname)s %(message)s') 236 | 237 | parser = argparse.ArgumentParser() 238 | parser.add_argument("--aws-region", default="us-east-1") 239 | parser.add_argument("--api-base-domain", required=True) 240 | parser.add_argument("--splunk-host", required=True) 241 | parser.add_argument("--splunk-token", required=True) 242 | parser.add_argument("--acct-id", required=True) 243 | parser.add_argument("--lambda-timeout", type=int, default=10) 244 | parser.add_argument("--lambda-memory", type=int, default=512) 245 | parser.add_argument("--kms-key", required=True) 246 | parser.add_argument("--subnet-list", nargs='+', required=True) 247 | parser.add_argument("--sg-list", nargs='+', required=True) 248 | parser.add_argument("--environment", required=True) 249 | parser.add_argument("--deployment", required=True) 250 | 251 | args = parser.parse_args() 252 | session = botocore.session.get_session() 253 | j2_env = Environment( 254 | loader=FileSystemLoader(os.path.join(os.path.dirname(__file__), 'templates')), 255 | trim_blocks=False 256 | ) 257 | tmpdirname = tempfile.mkdtemp() 258 | lambda_role_name = ( 259 | args.environment + '-' + args.deployment + '-' + 260 | 'lambda-basic-execution-monitor-cloudwatch-logs' 261 | ) 262 | lambda_function_name = args.environment + '-' + args.deployment + '-' + 'cloudwatch-logs-splunk' 263 | 264 | iam_client = session.create_client('iam', args.aws_region) 265 | cloudwatch_log_role_arn = \ 266 | create_role_with_managed_policy(iam_client, 267 | 'apigateway-to-cloudwatch-logs', 268 | '{"Version": "2012-10-17","Statement": ' 269 | '[{"Sid": "","Effect": "Allow","Principal": ' 270 | '{"Service": "apigateway.amazonaws.com"},' 271 | '"Action": "sts:AssumeRole"}]}', 272 | 'arn:aws:iam::aws:policy/service-role/' 273 | 'AmazonAPIGatewayPushToCloudWatchLogs') 274 | 275 | logging.info('Waiting for the newly created role to be available') 276 | # Sleep for 10 seconds to allow the role created above to be avialable 277 | time.sleep(10) 278 | api_client = session.create_client('apigateway', args.aws_region) 279 | (api_id, api_stage) = get_api_id(api_client, args.api_base_domain) 280 | add_cloudwatchlog_role_to_apigateway(api_client, cloudwatch_log_role_arn) 281 | 282 | api_gateway_name = get_api_gateway_name(api_client, api_id) 283 | sns_client = session.create_client('sns', args.aws_region) 284 | cw = session.create_client('cloudwatch', args.aws_region) 285 | 286 | create_api_alarm( 287 | cw_session=cw, alarm_name='api-gateway-count', metric='Count', namespace='ApiGateway', 288 | stat='Average', comparison='GreaterThanOrEqualToThreshold', 289 | description='Average API count for a period of 5 min', 290 | threshold=50, period=300, eval_period=1, 291 | dimensions=[ 292 | {'Name': 'ApiName', 'Value': api_gateway_name}, 293 | {'Name': 'Stage', 'Value': api_stage}, 294 | {'Name': 'ApiId', 'Value': api_id} 295 | ], 296 | topic=get_topic_arn(sns_client, 'aws-non-critical-alert') 297 | ) 298 | 299 | create_api_alarm( 300 | cw_session=cw, alarm_name='api-gateway-latency', metric='Latency', namespace='ApiGateway', 301 | stat='Average', comparison='GreaterThanOrEqualToThreshold', 302 | description='Average API Latency for a period of 5 min', 303 | threshold=3, period=300, eval_period=1, 304 | dimensions=[ 305 | {'Name': 'ApiName', 'Value': api_gateway_name}, 306 | {'Name': 'Stage', 'Value': api_stage}, 307 | {'Name': 'ApiId', 'Value': api_id} 308 | ], 309 | topic=get_topic_arn(sns_client, 'aws-non-critical-alert') 310 | ) 311 | 312 | create_api_alarm( 313 | cw_session=cw, alarm_name='api-gateway-errors-4xx', metric='4XXError', 314 | namespace='ApiGateway', stat='Average', comparison='GreaterThanOrEqualToThreshold', 315 | description='Average 4XX errors for a period of 5 min', 316 | threshold=4, period=300, eval_period=1, 317 | dimensions=[ 318 | {'Name': 'ApiName', 'Value': api_gateway_name}, 319 | {'Name': 'Stage', 'Value': api_stage}, 320 | {'Name': 'ApiId', 'Value': api_id} 321 | ], 322 | topic=get_topic_arn(sns_client, 'aws-non-critical-alert') 323 | ) 324 | 325 | create_api_alarm( 326 | cw_session=cw, alarm_name='api-gateway-errors-5xx', metric='5XXError', 327 | namespace='ApiGateway', stat='Average', comparison='GreaterThanOrEqualToThreshold', 328 | description='Average 5XX errors for a period of 5 min', 329 | threshold=4, period=300, eval_period=1, 330 | dimensions=[ 331 | {'Name': 'ApiName', 'Value': api_gateway_name}, 332 | {'Name': 'Stage', 'Value': api_stage}, 333 | {'Name': 'ApiId', 'Value': api_id} 334 | ], 335 | topic=get_topic_arn(sns_client, 'aws-non-critical-alert') 336 | ) 337 | 338 | with open( 339 | get_lambda_exec_policy( 340 | jinja_env=j2_env, 341 | temp_dir=tmpdirname, 342 | region=args.aws_region, 343 | acct_id=args.acct_id, 344 | func_name=lambda_function_name, 345 | kms_key=args.kms_key 346 | ), 347 | encoding='utf-8' 348 | ) as f: 349 | lambda_exec_role_arn = create_role_with_inline_policy( 350 | iam_client, 351 | lambda_role_name, 352 | '{"Version": "2012-10-17",' 353 | '"Statement": [{"Effect": "Allow","Principal": {"Service": "lambda.amazonaws.com"},' 354 | '"Action": "sts:AssumeRole"}]}', 355 | f.read() 356 | ) 357 | 358 | logging.info('Waiting for the newly created role to be available') 359 | # Sleep for 10 seconds to allow the role created above 360 | # to be available for lambda function creation 361 | time.sleep(10) 362 | attach_managed_policy(iam_client, lambda_role_name, 363 | 'arn:aws:iam::aws:policy/service-role/AWSLambdaVPCAccessExecutionRole') 364 | lambda_client = session.create_client('lambda', args.aws_region) 365 | zip_file_name = create_lambda_function_zip(j2_env, tmpdirname, args.splunk_host, 366 | args.splunk_token, lambda_function_name) 367 | vpc_config = {'SubnetIds': args.subnet_list, 'SecurityGroupIds': args.sg_list} 368 | create_lambda_function( 369 | client=lambda_client, 370 | function_name=lambda_function_name, 371 | runtime='nodejs18.x', 372 | role=lambda_exec_role_arn, 373 | handler='index.handler', 374 | zip_file=zip_file_name, 375 | description=( 376 | 'Demonstrates logging events to Splunk HTTP Event Collector,' 377 | ' accessing resources in a VPC' 378 | ), 379 | timeout=args.lambda_timeout, 380 | mem_size=args.lambda_memory, 381 | vpc=vpc_config 382 | ) 383 | try: 384 | shutil.rmtree(tmpdirname) 385 | except OSError as exc: 386 | logging.error(exc) 387 | logging.info('The lambda function is created, now in order to provide' 388 | ' event source to it, go to aws console, select the cloudwatch ' 389 | 'log group and select the action Start streaming to lambda') 390 | -------------------------------------------------------------------------------- /scripts/aws/templates/index.js.j2: -------------------------------------------------------------------------------- 1 | /** 2 | * According to our AWS correspondent this blueprint code is under the following license: 3 | * https://creativecommons.org/publicdomain/zero/1.0/ 4 | * 5 | * 6 | * Splunk-enabled logging function 7 | * 8 | * This function logs to a Splunk host using Splunk's event collector 9 | * API. API calls are authenticated using a long-lived event collector 10 | * token. 11 | * 12 | * Follow these steps to configure the function to log to your Splunk 13 | * host: 14 | * 15 | * 1. Insert your host and port in the splunkHost field. Default port 16 | * for the event collector is 8088. Make sure no firewalls will prevent 17 | * your Lambda function from connecting to this port on your host. 18 | * 19 | * 2. Create an event collector token for you function to use - 20 | * http://docs.splunk.com/Documentation/Splunk/6.3.0/Data/UsetheHTTPEventCollector#Create_an_Event_Collector_token 21 | * 22 | * 3. Create a KMS key - http://docs.aws.amazon.com/kms/latest/developerguide/create-keys.html 23 | * 24 | * 4. Encrypt the event collector token using the AWS CLI 25 | * aws kms encrypt --key-id alias/ --plaintext "" 26 | * 27 | * 5. Copy the base-64 encoded, encrypted token from step 4's CLI output 28 | * (CiphertextBlob attribute) to the base64EncodedEncryptedToken field on 29 | * the loggerInfo object in the "// User code" section in this file 30 | * 31 | * 6. Give your function's role permission for the kms:Decrypt action. 32 | * Example: 33 | 34 | { 35 | "Version": "2012-10-17", 36 | "Statement": [ 37 | { 38 | "Sid": "Stmt1443036478000", 39 | "Effect": "Allow", 40 | "Action": [ 41 | "kms:Decrypt" 42 | ], 43 | "Resource": [ 44 | "" 45 | ] 46 | } 47 | ] 48 | } 49 | 50 | */ 51 | // Library code 52 | var url = require('url'); 53 | var AWS = require('aws-sdk'); 54 | var zlib = require('zlib'); 55 | 56 | var initSplunkTokenAsync = function(loggerInfo) { 57 | var encryptedTokenBuf = new Buffer(loggerInfo.base64EncodedEncryptedToken, 'base64'); 58 | var kms = new AWS.KMS(); 59 | var params = { 60 | CiphertextBlob: encryptedTokenBuf 61 | }; 62 | kms.decrypt(params, function(err, data) { 63 | if (err) { 64 | loggerInfo.tokenInitError = err; 65 | console.log(err); 66 | } else { 67 | loggerInfo.decryptedToken = data.Plaintext.toString('ascii'); 68 | } 69 | }); 70 | }; 71 | 72 | var Logger = function(context) { 73 | var payloads = []; 74 | 75 | function log() { 76 | var time = Date.now(); 77 | var args = [time].concat(Array.prototype.slice.call(arguments)); 78 | logWithTime.apply(args); 79 | } 80 | 81 | function logWithTime() { 82 | var args = Array.prototype.slice.call(arguments); 83 | var payload = {}; 84 | var event = {}; 85 | if (args[1] !== null && typeof args[1] === 'object') { 86 | event.message = args[1]; 87 | } else { 88 | event.message = args.slice(1).join(' '); 89 | } 90 | 91 | if (typeof context !== 'undefined') { 92 | var reqId = context.awsRequestId; 93 | if (typeof reqId !== 'undefined') { 94 | event.awsRequestId = context.awsRequestId; 95 | } 96 | payload.source = context.functionName; 97 | } 98 | 99 | payload.time = new Date(args[0]).getTime() / 1000; 100 | payload.event = event; 101 | logEvent(payload); 102 | } 103 | 104 | function logEvent(payload) { 105 | payloads.push(JSON.stringify(payload)); 106 | } 107 | 108 | function flushAsync(callback) { 109 | // Check if we retrieved the decrypted token from KMS yet 110 | if (!loggerInfo.decryptedToken) { 111 | if (loggerInfo.tokenInitError) { 112 | console.log('Cannot flush logs since there was an error fetching the token for Splunk. Not retrying.'); 113 | return; 114 | } 115 | console.log('Cannot flush logs since authentication token has not been initialized yet. Trying again in 100 ms.'); 116 | setTimeout(function() { flushAsync(callback); }, 100); 117 | return; 118 | } 119 | var parsed = url.parse(loggerInfo.splunkHost); 120 | var options = { 121 | hostname: parsed.hostname, 122 | path: parsed.path, 123 | port: parsed.port, 124 | method: 'POST', 125 | headers: { 126 | 'Authorization': "Splunk " + loggerInfo.decryptedToken 127 | }, 128 | rejectUnauthorized: false, 129 | }; 130 | var requester = require(parsed.protocol.substring(0, parsed.protocol.length - 1)); 131 | var req = requester.request(options, function(res) { 132 | res.setEncoding('utf8'); 133 | 134 | console.log('Response received'); 135 | res.on('data', function(data) { 136 | if (res.statusCode != 200) { 137 | throw new Error("error: statusCode=" + res.statusCode + "\n\n" + data); 138 | } 139 | payloads.length = 0; 140 | if (typeof callback !== 'undefined') { 141 | callback(); 142 | } 143 | }); 144 | }); 145 | 146 | req.end(payloads.join(''), 'utf8'); 147 | } 148 | 149 | return { 150 | log: log, 151 | logEvent: logEvent, 152 | logWithTime: logWithTime, 153 | flushAsync: flushAsync 154 | }; 155 | }; 156 | 157 | 158 | // User code 159 | 160 | var loggerInfo = { 161 | splunkHost: 'https://{{ splunk_ip }}/services/collector', // Fill in with your Splunk host IP/DNS and port (step 1 above) 162 | base64EncodedEncryptedToken: '{{ token }}', // Fill in with base64-encoded, encrypted Splunk token here (step 5 above) 163 | lambdaFunctionName: '{{ lambda_function_name }}' 164 | }; 165 | 166 | initSplunkTokenAsync(loggerInfo); 167 | 168 | var glogger = new Logger({ functionName: loggerInfo.lambdaFunctionName }); 169 | glogger.log('Loading function'); 170 | glogger.flushAsync(); 171 | 172 | exports.handler = function(event, context) { 173 | var logger = new Logger(context); 174 | 175 | var decode = new Buffer(event.awslogs.data, 'base64'); 176 | zlib.gunzip(decode, function(e, result) { 177 | if (e) { 178 | context.fail(e); 179 | } else { 180 | result = JSON.parse(result.toString('ascii')); 181 | event.awslogs.data = result; 182 | 183 | //log JSON objects 184 | logger.log(event); 185 | logger.logWithTime(Date.now(), event); 186 | 187 | //send all the events in a single batch to Splunk 188 | logger.flushAsync(function() { 189 | context.succeed(event.key1); // Echo back the first key value 190 | }); 191 | } 192 | }); 193 | }; 194 | -------------------------------------------------------------------------------- /scripts/aws/templates/lambda_exec_policy.json.j2: -------------------------------------------------------------------------------- 1 | { 2 | "Version": "2012-10-17", 3 | "Statement": [ 4 | { 5 | "Effect": "Allow", 6 | "Action": [ 7 | "logs:CreateLogGroup", 8 | "logs:CreateLogStream", 9 | "logs:PutLogEvents" 10 | ], 11 | "Resource": "arn:aws:logs:{{ region }}:{{ acct_id }}:log-group:/aws/lambda/{{ func_name }}:*" 12 | }, 13 | { 14 | "Sid": "Stmt1443036478000", 15 | "Effect": "Allow", 16 | "Action": [ 17 | "kms:Decrypt" 18 | ], 19 | "Resource": [ 20 | "arn:aws:kms:{{ region }}:{{ acct_id }}:key/{{ kms_key }}" 21 | ] 22 | } 23 | ] 24 | } 25 | -------------------------------------------------------------------------------- /scripts/aws/tests/fixtures/swagger.json: -------------------------------------------------------------------------------- 1 | { 2 | "swagger": "2.0", 3 | "info": { 4 | "version": "0.0.0", 5 | "title": "test" 6 | }, 7 | "host": "api.example.org", 8 | "basePath": "/", 9 | "schemes": [ 10 | "https" 11 | ], 12 | "paths": { 13 | "/": { 14 | "get": { 15 | "consumes": [ 16 | "application/json" 17 | ], 18 | "produces": [ 19 | "application/json" 20 | ], 21 | "responses": { 22 | "200": { 23 | "description": "OK" 24 | } 25 | }, 26 | "x-amazon-apigateway-integration": { 27 | "responses": { 28 | "default": { 29 | "statusCode": "200", 30 | "responseTemplates": { 31 | "application/json": "{\"hello\": \"world\"}" 32 | } 33 | } 34 | }, 35 | "requestTemplates": { 36 | "application/json": "{\"statusCode\": 200}" 37 | }, 38 | "type": "mock" 39 | } 40 | } 41 | } 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /scripts/aws/tests/test_bootstrap.py: -------------------------------------------------------------------------------- 1 | """ 2 | Tests for scripts/aws/bootstrap.py 3 | """ 4 | import boto3 5 | import pytest 6 | from unittest import TestCase 7 | from bootstrap import get_domain, get_base_path, create_apigw_custom_domain_name,\ 8 | create_route53_rs, bootstrap_api, create_base_path_mapping, file_arg_to_string 9 | 10 | 11 | class BootstrapTest(TestCase): 12 | """ 13 | TestCase class for testing bootstrap.py 14 | """ 15 | 16 | def setUp(self): 17 | self.api_base_domain = 'api.fake-host.com' 18 | self.cloudfront_zone = 'fake-zone' 19 | self.distribution_name = 'fake-distro' 20 | 21 | @pytest.mark.skip(reason="moto does not yet support AWS:ApiGateway:GetDomainName") 22 | def test_get_domain(self): 23 | pass 24 | 25 | @pytest.mark.skip(reason="moto does not yet support AWS:ApiGateway:GetBasePathMapping") 26 | def test_get_base_path(self): 27 | pass 28 | 29 | @pytest.mark.skip(reason="moto does not yet support AWS:ApiGateway:CreateDomainName") 30 | def test_create_apigw_custom_domain_name(self): 31 | pass 32 | 33 | @pytest.mark.skip(reason="moto does not yet support AWS:Route53:ChangeResourceRecordSets") 34 | def test_create_route53_rs(self): 35 | pass 36 | -------------------------------------------------------------------------------- /scripts/aws/tests/test_deploy_common.py: -------------------------------------------------------------------------------- 1 | """ 2 | Tests for scripts/aws/common/deploy.py 3 | """ 4 | import boto3 5 | import pytest 6 | from moto import mock_aws 7 | from unittest import TestCase 8 | from common.deploy import get_api_id, get_next_stage, deploy_api, update_stage 9 | 10 | 11 | class DeployTest(TestCase): 12 | """ 13 | TestCase class for testing deploy.py 14 | """ 15 | 16 | @mock_aws 17 | def setUp(self): 18 | self.rotation = ['red', 'black', 'turquoise'] 19 | self.current_stage = 'black' 20 | self.api_base_domain = 'api.fake-host.com' 21 | self.swagger_filename = 'fixtures/swagger.json' 22 | 23 | @pytest.mark.skip(reason="moto does not yet support AWS:ApiGateway:GetBasePathMapping") 24 | @mock_aws 25 | def test_get_api_id(self): 26 | pass 27 | 28 | # Test the ring-based iteration logic 29 | def test_get_next_stage(self): 30 | 31 | # list of {current: next} keypairs 32 | expected_rotations = [ 33 | {'current': 'red', 'next': 'black'}, 34 | {'current': 'black', 'next': 'turquoise'}, 35 | {'current': 'turquoise', 'next': 'red'}, 36 | {'current': 'not-in-rotation', 'next': 'red'} 37 | ] 38 | 39 | for expected_rotation in expected_rotations: 40 | actual_next_stage = get_next_stage(self.rotation, expected_rotation['current']) 41 | self.assertEqual(expected_rotation['next'], actual_next_stage) 42 | 43 | # test behavior with a bad rotation 44 | with self.assertRaises(ValueError): 45 | get_next_stage([], 'red') 46 | 47 | @pytest.mark.skip(reason="moto does not yet support AWS:ApiGateway:PutRestApi") 48 | @mock_aws 49 | def test_deploy_api(self): 50 | pass 51 | 52 | @pytest.mark.skip(reason="moto does not yet support AWS:ApiGateway:UpdateStage") 53 | @mock_aws 54 | def test_update_stage(self): 55 | pass 56 | -------------------------------------------------------------------------------- /scripts/aws/tests/test_flip.py: -------------------------------------------------------------------------------- 1 | """ 2 | Tests for scripts/aws/flip.py 3 | """ 4 | import boto3 5 | import pytest 6 | from unittest import TestCase 7 | from flip import get_live_stage, update_base_path_mapping 8 | 9 | 10 | class FlipTest(TestCase): 11 | """ 12 | TestCase class for testing flip.py 13 | """ 14 | 15 | def setUp(self): 16 | self.api_base_domain = 'api.fake-host.com' 17 | self.rotation = ['red', 'black', 'turquoise'] 18 | self.current_stage = 'black' 19 | self.next_stage = 'turquoise' 20 | 21 | @pytest.mark.skip(reason="moto does not yet support AWS:ApiGateway:GetBasePathMapping") 22 | def test_get_live_stage(self): 23 | pass 24 | 25 | @pytest.mark.skip(reason="moto does not yet support AWS:ApiGateway:UpdateBasePathMapping") 26 | def test_update_base_path_mapping(self): 27 | pass 28 | -------------------------------------------------------------------------------- /swagger/api.yaml: -------------------------------------------------------------------------------- 1 | # Swagger specification for the Open edX API 2 | # Note: not all API endpoints need to be listed here, just those that 3 | # are part of your Open edX installation's "public API". 4 | 5 | --- 6 | swagger: "2.0" 7 | info: 8 | version: "1.0.0" 9 | title: "Open edX" 10 | host: "your-open-edx-site.org" 11 | basePath: "/" 12 | schemes: 13 | - "https" 14 | 15 | # Complete set of whitelisted routes. 16 | # Upstream API owners: provide an fixed URI ref for each route. 17 | paths: 18 | 19 | # Index 20 | "/": 21 | $ref: "./index.yaml#/endpoints/index" 22 | 23 | # Heartbeat 24 | "/heartbeat": 25 | $ref: "./heartbeat.yaml#/endpoints/heartbeat" 26 | 27 | # OAuth2 28 | "/oauth2/v1/access_token": 29 | $ref: "./oauth.yaml#/endpoints/request_access_token" 30 | 31 | # Catalog IDA 32 | "/catalog/v1/catalogs": 33 | $ref: "https://raw.githubusercontent.com/edx/course-discovery/b5c52c8/api.yaml#/endpoints/v1/catalogs" 34 | "/catalog/v1/catalogs/{id}": 35 | $ref: "https://raw.githubusercontent.com/edx/course-discovery/b5c52c8/api.yaml#/endpoints/v1/catalogById" 36 | "/catalog/v1/catalogs/{id}/courses": 37 | $ref: "https://raw.githubusercontent.com/edx/course-discovery/b5c52c8/api.yaml#/endpoints/v1/catalogCourses" 38 | 39 | 40 | 41 | # Enterprise IDA 42 | "/enterprise/v1/enterprise-catalogs": 43 | $ref: "https://raw.githubusercontent.com/edx/edx-enterprise/260055b/api.yaml#/endpoints/v1/enterpriseCustomerCatalogs" 44 | "/enterprise/v1/enterprise-catalogs/{uuid}": 45 | $ref: "https://raw.githubusercontent.com/edx/edx-enterprise/260055b/api.yaml#/endpoints/v1/enterpriseCustomerCatalogByUuid" 46 | "/enterprise/v1/enterprise-catalogs/{uuid}/course-runs/{course_run_id}": 47 | $ref: "https://raw.githubusercontent.com/edx/edx-enterprise/260055b/api.yaml#/endpoints/v1/enterpriseCustomerCatalogCourseRunByUuid" 48 | "/enterprise/v1/enterprise-catalogs/{uuid}/courses/{course_key}": 49 | $ref: "https://raw.githubusercontent.com/edx/edx-enterprise/260055b/api.yaml#/endpoints/v1/enterpriseCustomerCatalogCourseByKey" 50 | "/enterprise/v1/enterprise-catalogs/{uuid}/programs/{program_uuid}": 51 | $ref: "https://raw.githubusercontent.com/edx/edx-enterprise/260055b/api.yaml#/endpoints/v1/enterpriseCustomerCatalogProgramByUuid" 52 | "/enterprise/v1/enterprise-customer/{uuid}/course-enrollments": 53 | $ref: "https://raw.githubusercontent.com/edx/edx-enterprise/260055b/api.yaml#/endpoints/v1/enterpriseCustomerCourseEnrollments" 54 | "/enterprise/v1/enterprise-customer/{uuid}/learner-summary": 55 | $ref: "https://raw.githubusercontent.com/edx/edx-enterprise-data/eb793cf/api.yaml#/endpoints/v1/enterpriseCustomerLearnerSummary" 56 | # License Manager IDA 57 | # These are served from the license manager IDA, but we surface them with the rest of the enterprise endpoints 58 | "/enterprise/v1/subscriptions": 59 | $ref: "https://raw.githubusercontent.com/edx/license-manager/b7dc6e0/api.yaml#/endpoints/v1/subscriptionsList" 60 | "/enterprise/v1/subscriptions/{uuid}/licenses/assign": 61 | $ref: "https://raw.githubusercontent.com/edx/license-manager/ef94bee/api.yaml#/endpoints/v1/assignLicenses" 62 | "/enterprise/v1/subscriptions/{uuid}/licenses/bulk-revoke": 63 | $ref: "https://raw.githubusercontent.com/edx/license-manager/b9e9ec9/api.yaml#/endpoints/v1/revokeLicenses" 64 | "/enterprise/v1/bulk-license-enrollment": 65 | $ref: "https://raw.githubusercontent.com/edx/license-manager/b9e9ec9/api.yaml#/endpoints/v1/bulkLicenseEnrollment" 66 | # Enterprise Access IDA 67 | # These are served from the enterprise-access IDA, but we surface them with the rest of the enterprise endpoints 68 | "/enterprise/v1/assignment-configurations/{assignment_configuration_uuid}/admin/assignments/": 69 | $ref: "https://raw.githubusercontent.com/openedx/enterprise-access/b2d181e/api.yaml#/endpoints/v1/learnerContentAssignmentListRequest" 70 | "/enterprise/v1/assignment-configurations/{assignment_configuration_uuid}/admin/assignments/cancel/": 71 | $ref: "https://raw.githubusercontent.com/openedx/enterprise-access/7b79f45/api.yaml#/endpoints/v1/learnerContentAssignmentCancelRequest" 72 | "/enterprise/v1/assignment-configurations/{assignment_configuration_uuid}/admin/assignments/remind/": 73 | $ref: "https://raw.githubusercontent.com/openedx/enterprise-access/7b79f45/api.yaml#/endpoints/v1/learnerContentAssignmentRemindRequest" 74 | "/enterprise/v1/policy-allocation/{policy_uuid}/allocate/": 75 | $ref: "https://raw.githubusercontent.com/openedx/enterprise-access/7b79f45/api.yaml#/endpoints/v1/subsidyAccessPolicyAllocation" 76 | "/enterprise/v1/subsidy-access-policies/": 77 | $ref: "https://raw.githubusercontent.com/openedx/enterprise-access/5a8ea18/api.yaml#/endpoints/v1/subsidyAccessPolicies" 78 | # Enterprise Catalog IDA 79 | # These are served from the enterprise catalog IDA, but we surface them with the rest of the enterprise endpoints 80 | "/enterprise/v2/enterprise-catalogs": 81 | $ref: "https://raw.githubusercontent.com/edx/enterprise-catalog/2877ad7/api.yaml#/endpoints/v2/enterpriseCatalogs" 82 | "/enterprise/v2/enterprise-catalogs/{uuid}": 83 | $ref: "https://raw.githubusercontent.com/edx/enterprise-catalog/2877ad7/api.yaml#/endpoints/v2/enterpriseCatalogByUuid" 84 | # Add the following v1 endpoints to v2 with the same implementation for ease of use by the ECS team 85 | "/enterprise/v2/enterprise-catalogs/{uuid}/course-runs/{course_run_id}": 86 | $ref: "https://raw.githubusercontent.com/edx/edx-enterprise/260055b/api.yaml#/endpoints/v1/enterpriseCustomerCatalogCourseRunByUuid" 87 | "/enterprise/v2/enterprise-catalogs/{uuid}/courses/{course_key}": 88 | $ref: "https://raw.githubusercontent.com/edx/edx-enterprise/260055b/api.yaml#/endpoints/v1/enterpriseCustomerCatalogCourseByKey" 89 | "/enterprise/v2/enterprise-catalogs/{uuid}/programs/{program_uuid}": 90 | $ref: "https://raw.githubusercontent.com/edx/edx-enterprise/260055b/api.yaml#/endpoints/v1/enterpriseCustomerCatalogProgramByUuid" 91 | "/enterprise/v2/enterprise-customer/{uuid}/course-enrollments": 92 | $ref: "https://raw.githubusercontent.com/edx/edx-enterprise/260055b/api.yaml#/endpoints/v1/enterpriseCustomerCourseEnrollments" 93 | "/enterprise/v2/enterprise-customer/{uuid}/learner-summary": 94 | $ref: "https://raw.githubusercontent.com/edx/edx-enterprise-data/eb793cf/api.yaml#/endpoints/v1/enterpriseCustomerLearnerSummary" 95 | # Learner Summary endpoint powered by Learner Progress Report V1 API 96 | "/enterprise/v3/enterprise-customer/{uuid}/learner-summary": 97 | $ref: "https://raw.githubusercontent.com/edx/edx-enterprise-data/eb793cf/api.yaml#/endpoints/v2/enterpriseCustomerLearnerSummary" 98 | 99 | # Registrar API Proxy 100 | # Note: There's an unresolved issue involving trailing slashes with proxy integrations in API Gateway. 101 | # Apparently all trailing slashes included in the value of {proxy} are trimmed, see this AWS 102 | # support forum thread: https://forums.aws.amazon.com/thread.jspa?messageID=749625 103 | # Our registrar API endpoint paths require trailing slashes, but other registrar paths, like those 104 | # under /static, cannot have them. Thus, we've broken apart the different path types under registrar. 105 | # This means that this specification must be updated each time a new version of the 106 | # registrar API is released. 107 | 108 | "/registrar/api-docs": 109 | x-amazon-apigateway-any-method: 110 | x-amazon-apigateway-integration: 111 | type: "http_proxy" 112 | uri: "https://${stageVariables.registrar_host}/api-docs/" 113 | httpMethod: "ANY" 114 | 115 | "/registrar/login": 116 | x-amazon-apigateway-any-method: 117 | x-amazon-apigateway-integration: 118 | type: "http_proxy" 119 | uri: "https://${stageVariables.registrar_host}/login/" 120 | httpMethod: "ANY" 121 | 122 | "/registrar/logout": 123 | x-amazon-apigateway-any-method: 124 | x-amazon-apigateway-integration: 125 | type: "http_proxy" 126 | uri: "https://${stageVariables.registrar_host}/logout/" 127 | httpMethod: "ANY" 128 | 129 | "/registrar/static/{proxy+}": 130 | x-amazon-apigateway-any-method: 131 | parameters: 132 | - name: "proxy" 133 | in: "path" 134 | x-amazon-apigateway-integration: 135 | type: "http_proxy" 136 | uri: "https://${stageVariables.registrar_host}/static/{proxy}" 137 | httpMethod: "ANY" 138 | requestParameters: 139 | integration.request.path.proxy: "method.request.path.proxy" 140 | 141 | "/registrar/v1/{proxy+}": 142 | x-amazon-apigateway-any-method: 143 | parameters: 144 | - name: "proxy" 145 | in: "path" 146 | x-amazon-apigateway-integration: 147 | type: "http_proxy" 148 | uri: "https://${stageVariables.registrar_host}/api/v1/{proxy}/" 149 | httpMethod: "ANY" 150 | requestParameters: 151 | integration.request.path.proxy: "method.request.path.proxy" 152 | 153 | "/registrar/v2/{proxy+}": 154 | x-amazon-apigateway-any-method: 155 | parameters: 156 | - name: "proxy" 157 | in: "path" 158 | x-amazon-apigateway-integration: 159 | type: "http_proxy" 160 | uri: "https://${stageVariables.registrar_host}/api/v2/{proxy}/" 161 | httpMethod: "ANY" 162 | requestParameters: 163 | integration.request.path.proxy: "method.request.path.proxy" 164 | 165 | # Authoring Domain API (e.g. content ingestion via CMS) 166 | "/authoring/v0/file_assets/{proxy+}": 167 | x-amazon-apigateway-any-method: 168 | parameters: 169 | - name: "proxy" 170 | in: "path" 171 | x-amazon-apigateway-integration: 172 | type: "http_proxy" 173 | uri: "https://${stageVariables.authoring_host}/api/contentstore/v0/file_assets/{proxy}" 174 | httpMethod: "ANY" 175 | requestParameters: 176 | integration.request.path.proxy: "method.request.path.proxy" 177 | 178 | "/authoring/v0/videos/uploads/{proxy+}": 179 | x-amazon-apigateway-any-method: 180 | parameters: 181 | - name: "proxy" 182 | in: "path" 183 | x-amazon-apigateway-integration: 184 | type: "http_proxy" 185 | uri: "https://${stageVariables.authoring_host}/api/contentstore/v0/videos/uploads/{proxy}" 186 | httpMethod: "ANY" 187 | requestParameters: 188 | integration.request.path.proxy: "method.request.path.proxy" 189 | 190 | "/authoring/v0/videos/images/{proxy+}": 191 | x-amazon-apigateway-any-method: 192 | parameters: 193 | - name: "proxy" 194 | in: "path" 195 | x-amazon-apigateway-integration: 196 | type: "http_proxy" 197 | uri: "https://${stageVariables.authoring_host}/api/contentstore/v0/videos/images/{proxy}" 198 | httpMethod: "ANY" 199 | requestParameters: 200 | integration.request.path.proxy: "method.request.path.proxy" 201 | 202 | "/authoring/v0/video_transcripts/{proxy+}": 203 | x-amazon-apigateway-any-method: 204 | parameters: 205 | - name: "proxy" 206 | in: "path" 207 | x-amazon-apigateway-integration: 208 | type: "http_proxy" 209 | uri: "https://${stageVariables.authoring_host}/api/contentstore/v0/video_transcripts/{proxy}" 210 | httpMethod: "ANY" 211 | requestParameters: 212 | integration.request.path.proxy: "method.request.path.proxy" 213 | 214 | "/authoring/v0/xblock/{proxy+}": 215 | x-amazon-apigateway-any-method: 216 | parameters: 217 | - name: "proxy" 218 | in: "path" 219 | x-amazon-apigateway-integration: 220 | type: "http_proxy" 221 | uri: "https://${stageVariables.authoring_host}/api/contentstore/v0/xblock/{proxy}" 222 | httpMethod: "ANY" 223 | requestParameters: 224 | integration.request.path.proxy: "method.request.path.proxy" 225 | 226 | 227 | 228 | # edX extension point. Lists the vendors in use and their specific 229 | # parameters that are expected by upstream refs. 230 | # Upstream API owners: document your dependencies in this index file to 231 | # avoid conflicts with other upstreams. 232 | x-edx-api-vendors: 233 | aws_apigateway: 234 | stage_variables: 235 | - "id" 236 | - "landing_page" 237 | - "edxapp_host" 238 | - "discovery_host" 239 | - "enterprise_host" 240 | - "gateway_host" 241 | - "analytics_api_host" 242 | - "registrar_host" 243 | - "enterprise_catalog_host" 244 | - "authoring_host" 245 | - "license_manager_host" 246 | - "enterprise_access_host" 247 | -------------------------------------------------------------------------------- /swagger/heartbeat.yaml: -------------------------------------------------------------------------------- 1 | --- 2 | # This is a Swagger (swagger.org) specification fragment. It is 3 | # designed to be included into a top-level Swagger 'index', not 4 | # as a standalone document. 5 | 6 | endpoints: 7 | heartbeat: 8 | get: 9 | operationId: "get_heartbeat" 10 | tags: 11 | - heartbeat 12 | description: | 13 | This endpoint returns basic "vital signs" for the Open edX API manager 14 | in question. It can be used as a simple up/down liveness test or for a 15 | more detailed (but still lightweight) analysis of the system. 16 | consumes: 17 | - "application/json" 18 | produces: 19 | - "application/json" 20 | responses: 21 | 200: 22 | description: "OK" 23 | schema: 24 | title: "heartbeat" 25 | type: object 26 | properties: 27 | version: 28 | type: "string" 29 | description: | 30 | Open edX API version, typically represented as "major.minor.micro". 31 | The versioning lifecycle rules will be specific to your Open edX installation. 32 | # example: "1.0.0" 33 | id: 34 | type: "string" 35 | description: | 36 | Unique configuration deployment identification code, optional and specific to 37 | your Open edX installation. For example, this value could be the git hash of 38 | the configuration used to spin up the API manager. 39 | # example: "7effb8a" 40 | required: 41 | - version 42 | x-amazon-apigateway-integration: 43 | responses: 44 | default: 45 | statusCode: "200" 46 | responseTemplates: 47 | application/json: | 48 | { 49 | "version": "1.0.0", 50 | "id": "${stageVariables['id']}" 51 | } 52 | requestTemplates: 53 | application/json: | 54 | {"statusCode": 200} 55 | type: "mock" 56 | -------------------------------------------------------------------------------- /swagger/index.yaml: -------------------------------------------------------------------------------- 1 | --- 2 | # This is a Swagger (swagger.org) specification fragment. It is 3 | # designed to be included into a top-level Swagger 'index', not 4 | # as a standalone document. 5 | 6 | endpoints: 7 | index: 8 | get: 9 | operationId: "get_index" 10 | tags: 11 | - index 12 | description: | 13 | This endpoint returns a redirect to the API's landing page 14 | (documentation, developer portal, etc). It is optional. 15 | produces: 16 | - "text/html" 17 | responses: 18 | 302: 19 | description: "Redirect" 20 | headers: 21 | Location: 22 | type: "string" 23 | x-amazon-apigateway-integration: 24 | responses: 25 | default: 26 | statusCode: "302" 27 | responseParameters: 28 | method.response.header.Location: "stageVariables.landing_page" 29 | requestTemplates: 30 | application/json: | 31 | {"statusCode": 302} 32 | type: "mock" 33 | -------------------------------------------------------------------------------- /swagger/oauth.yaml: -------------------------------------------------------------------------------- 1 | --- 2 | # This is a Swagger (swagger.org) specification fragment. It is 3 | # designed to be included into a top-level Swagger 'index', not 4 | # as a standalone document. 5 | 6 | endpoints: 7 | request_access_token: 8 | post: 9 | operationId: request_access_token 10 | tags: 11 | - oauth2 12 | description: | 13 | To request an access token, the client obtains authorization from the 14 | resource owner. The authorization is expressed in the form of an 15 | authorization grant, which the client uses to request the access 16 | token. See https://tools.ietf.org/html/rfc6749#section-4 for more detail. 17 | parameters: 18 | - in: formData 19 | name: grant_type 20 | required: true 21 | type: string 22 | - in: formData 23 | name: client_id 24 | required: true 25 | type: string 26 | - in: formData 27 | name: client_secret 28 | required: false 29 | type: string 30 | format: password 31 | - in: formData 32 | name: token_type 33 | required: false 34 | type: string 35 | - in: formData 36 | name: username 37 | required: false 38 | type: string 39 | - in: formData 40 | name: password 41 | required: false 42 | type: string 43 | format: password 44 | - in: formData 45 | name: refresh_token 46 | required: false 47 | type: string 48 | format: password 49 | consumes: 50 | - application/x-www-form-urlencoded 51 | produces: 52 | - application/json 53 | responses: 54 | 200: 55 | description: OK 56 | schema: 57 | type: object 58 | title: "bearer" 59 | properties: 60 | access_token: 61 | type: "string" 62 | description: "The access token issued by the authorization server." 63 | # example: "2YotnFZFEjr1zCsicMWpAA" 64 | refresh_token: 65 | type: "string" 66 | description: | 67 | Refresh tokens are credentials used to obtain new access tokens once 68 | authorization has already been granted. 69 | # example: "tGzv3JOkF0XG5Qx2TlKWIA" 70 | scope: 71 | type: "string" 72 | description: | 73 | Whitespace-delimited list of associated scopes. Can be an empty string. 74 | See https://tools.ietf.org/html/rfc6749#section-3.3 for more detail. 75 | # example: "read write" 76 | token_type: 77 | type: "string" 78 | description: "The type of the token issued. Value is case insensitive." 79 | # example: "Bearer" 80 | expires_in: 81 | type: "integer" 82 | format: "int64" 83 | description: "The lifetime in seconds of the access token." 84 | # example: 60 85 | required: 86 | - access_token 87 | - scope 88 | - token_type 89 | - expires_in 90 | 400: 91 | description: "Bad Request" 92 | 401: 93 | description: Unauthorized 94 | 403: 95 | description: Forbidden 96 | 404: 97 | description: "Not Found" 98 | 429: 99 | description: "Too Many Requests" 100 | 500: 101 | description: "Internal Server Error" 102 | x-amazon-apigateway-auth: 103 | type: none 104 | x-amazon-apigateway-integration: 105 | httpMethod: POST 106 | responses: 107 | 200: 108 | statusCode: "200" 109 | 401: 110 | statusCode: "401" 111 | 403: 112 | statusCode: "403" 113 | 404: 114 | statusCode: "404" 115 | 429: 116 | statusCode: "429" 117 | 500: 118 | statusCode: "500" 119 | default: 120 | statusCode: "400" 121 | type: http 122 | uri: "https://${stageVariables.edxapp_host}/oauth2/access_token" 123 | -------------------------------------------------------------------------------- /tests/test_all.yaml: -------------------------------------------------------------------------------- 1 | --- 2 | - import: 'tests/test_heartbeat.yaml' 3 | - import: 'tests/test_index.yaml' 4 | - import: 'tests/test_oauth.yaml' 5 | - import: 'tests/test_catalog.yaml' 6 | - import: 'tests/test_enterprise.yaml' 7 | - import: 'tests/test_enterprise_access.yaml' 8 | -------------------------------------------------------------------------------- /tests/test_catalog.yaml: -------------------------------------------------------------------------------- 1 | --- 2 | - config: 3 | - testset: 'Catalog API' 4 | 5 | - test: 6 | - name: 'Catalogs endpoint returns HTTP 200' 7 | - url: '/catalog/v1/catalogs' 8 | - method: 'GET' 9 | - headers: {'Authorization': 'aeiou'} 10 | - expected_status: [200] 11 | 12 | - test: 13 | - name: 'Catalog by ID endpoint returns HTTP 200' 14 | - url: '/catalog/v1/catalogs/1' 15 | - method: 'GET' 16 | - headers: {'Authorization': 'aeiou'} 17 | - expected_status: [200] 18 | 19 | - test: 20 | - name: 'Catalog courses endpoint returns HTTP 200' 21 | - url: '/catalog/v1/catalogs/1/courses' 22 | - method: 'GET' 23 | - headers: {'Authorization': 'aeiou'} 24 | - expected_status: [200] 25 | 26 | - test: 27 | - name: 'POST is disabled for catalogs' 28 | - url: '/catalog/v1/catalogs' 29 | - method: 'POST' 30 | - headers: {'Authorization': 'aeiou'} 31 | - expected_status: [405] 32 | 33 | - test: 34 | - name: 'GET rejected without authorization' 35 | - url: '/catalog/v1/catalogs' 36 | - method: 'GET' 37 | - expected_status: [400] 38 | -------------------------------------------------------------------------------- /tests/test_enterprise.yaml: -------------------------------------------------------------------------------- 1 | --- 2 | - config: 3 | - testset: 'Enterprise API' 4 | 5 | - test: 6 | - name: 'Enterprise catalog endpoint returns HTTP 200' 7 | - url: '/enterprise/v1/enterprise-catalogs' 8 | - method: 'GET' 9 | - headers: {'Authorization': 'aeiou'} 10 | - expected_status: [200] 11 | 12 | - test: 13 | - name: 'Enterprise catalog version 2 endpoint returns HTTP 200' 14 | - url: '/enterprise/v2/enterprise-catalogs' 15 | - method: 'GET' 16 | - headers: {'Authorization': 'aeiou'} 17 | - expected_status: [200] 18 | 19 | - test: 20 | - name: 'Enterprise catalog by UUID endpoint returns HTTP 200' 21 | - url: '/enterprise/v1/enterprise-catalogs/0123456789abcdefg' 22 | - method: 'GET' 23 | - headers: {'Authorization': 'aeiou'} 24 | - expected_status: [200] 25 | 26 | - test: 27 | - name: 'Enterprise catalog by UUID endpoint version 2 returns HTTP 200' 28 | - url: '/enterprise/v2/enterprise-catalogs/0123456789abcdefg' 29 | - method: 'GET' 30 | - headers: {'Authorization': 'aeiou'} 31 | - expected_status: [200] 32 | 33 | - test: 34 | - name: 'Course run by ID endpoint returns HTTP 200' 35 | - url: '/enterprise/v1/enterprise-catalogs/0123456789abcdefg/course-runs/0123456789abcdefg' 36 | - method: 'GET' 37 | - headers: {'Authorization': 'aeiou'} 38 | - expected_status: [200] 39 | 40 | - test: 41 | - name: 'Course run by ID endpoint v2 returns HTTP 200' 42 | - url: '/enterprise/v2/enterprise-catalogs/0123456789abcdefg/course-runs/0123456789abcdefg' 43 | - method: 'GET' 44 | - headers: {'Authorization': 'aeiou'} 45 | - expected_status: [200] 46 | 47 | - test: 48 | - name: 'Course by key endpoint returns HTTP 200' 49 | - url: '/enterprise/v1/enterprise-catalogs/0123456789abcdefg/courses/0123456789abcdefg' 50 | - method: 'GET' 51 | - headers: {'Authorization': 'aeiou'} 52 | - expected_status: [200] 53 | 54 | - test: 55 | - name: 'Course by key endpoint v2 returns HTTP 200' 56 | - url: '/enterprise/v2/enterprise-catalogs/0123456789abcdefg/courses/0123456789abcdefg' 57 | - method: 'GET' 58 | - headers: {'Authorization': 'aeiou'} 59 | - expected_status: [200] 60 | 61 | - test: 62 | - name: 'Program by UUID endpoint returns HTTP 200' 63 | - url: '/enterprise/v1/enterprise-catalogs/0123456789abcdefg/programs/0123456789abcdefg' 64 | - method: 'GET' 65 | - headers: {'Authorization': 'aeiou'} 66 | - expected_status: [200] 67 | 68 | - test: 69 | - name: 'Program by UUID endpoint v2 returns HTTP 200' 70 | - url: '/enterprise/v2/enterprise-catalogs/0123456789abcdefg/programs/0123456789abcdefg' 71 | - method: 'GET' 72 | - headers: {'Authorization': 'aeiou'} 73 | - expected_status: [200] 74 | 75 | - test: 76 | - name: 'Enterprise catalog POST is disabled' 77 | - url: '/enterprise/v1/enterprise-catalogs' 78 | - method: 'POST' 79 | - headers: {'Authorization': 'aeiou'} 80 | - expected_status: [405] 81 | 82 | - test: 83 | - name: 'Enterprise catalog version 2 POST is disabled' 84 | - url: '/enterprise/v2/enterprise-catalogs' 85 | - method: 'POST' 86 | - headers: {'Authorization': 'aeiou'} 87 | - expected_status: [405] 88 | 89 | - test: 90 | - name: 'Enterprise catalog GET rejected without authorization' 91 | - url: '/enterprise/v1/enterprise-catalogs' 92 | - method: 'GET' 93 | - expected_status: [400] 94 | 95 | - test: 96 | - name: 'Enterprise catalog version 2 GET rejected without authorization' 97 | - url: '/enterprise/v2/enterprise-catalogs' 98 | - method: 'GET' 99 | - expected_status: [400] 100 | 101 | - test: 102 | - name: 'Enterprise course run POST is disabled' 103 | - url: '/enterprise/v1/enterprise-catalogs/0123456789abcdefg/course-runs/0123456789abcdefg' 104 | - method: 'POST' 105 | - headers: {'Authorization': 'aeiou'} 106 | - expected_status: [405] 107 | 108 | - test: 109 | - name: 'Enterprise course run v2 POST is disabled' 110 | - url: '/enterprise/v2/enterprise-catalogs/0123456789abcdefg/course-runs/0123456789abcdefg' 111 | - method: 'POST' 112 | - headers: {'Authorization': 'aeiou'} 113 | - expected_status: [405] 114 | 115 | - test: 116 | - name: 'Enterprise course POST is disabled' 117 | - url: '/enterprise/v1/enterprise-catalogs/0123456789abcdefg/courses/0123456789abcdefg' 118 | - method: 'POST' 119 | - headers: {'Authorization': 'aeiou'} 120 | - expected_status: [405] 121 | 122 | - test: 123 | - name: 'Enterprise course v2 POST is disabled' 124 | - url: '/enterprise/v2/enterprise-catalogs/0123456789abcdefg/courses/0123456789abcdefg' 125 | - method: 'POST' 126 | - headers: {'Authorization': 'aeiou'} 127 | - expected_status: [405] 128 | 129 | - test: 130 | - name: 'Enterprise program POST is disabled' 131 | - url: '/enterprise/v1/enterprise-catalogs/0123456789abcdefg/programs/0123456789abcdefg' 132 | - method: 'POST' 133 | - headers: {'Authorization': 'aeiou'} 134 | - expected_status: [405] 135 | 136 | - test: 137 | - name: 'Enterprise program v2 POST is disabled' 138 | - url: '/enterprise/v2/enterprise-catalogs/0123456789abcdefg/programs/0123456789abcdefg' 139 | - method: 'POST' 140 | - headers: {'Authorization': 'aeiou'} 141 | - expected_status: [405] 142 | 143 | - test: 144 | - name: 'Enterprise course run GET rejected without authorization' 145 | - url: '/enterprise/v1/enterprise-catalogs/0123456789abcdefg/course-runs/0123456789abcdefg' 146 | - method: 'GET' 147 | - expected_status: [400] 148 | 149 | - test: 150 | - name: 'Enterprise course run v2 GET rejected without authorization' 151 | - url: '/enterprise/v2/enterprise-catalogs/0123456789abcdefg/course-runs/0123456789abcdefg' 152 | - method: 'GET' 153 | - expected_status: [400] 154 | 155 | - test: 156 | - name: 'Enterprise course GET rejected without authorization' 157 | - url: '/enterprise/v1/enterprise-catalogs/0123456789abcdefg/courses/0123456789abcdefg' 158 | - method: 'GET' 159 | - expected_status: [400] 160 | 161 | - test: 162 | - name: 'Enterprise course v2 GET rejected without authorization' 163 | - url: '/enterprise/v2/enterprise-catalogs/0123456789abcdefg/courses/0123456789abcdefg' 164 | - method: 'GET' 165 | - expected_status: [400] 166 | 167 | - test: 168 | - name: 'Enterprise program GET rejected without authorization' 169 | - url: '/enterprise/v1/enterprise-catalogs/0123456789abcdefg/programs/0123456789abcdefg' 170 | - method: 'GET' 171 | - expected_status: [400] 172 | 173 | - test: 174 | - name: 'Enterprise program v2 GET rejected without authorization' 175 | - url: '/enterprise/v2/enterprise-catalogs/0123456789abcdefg/programs/0123456789abcdefg' 176 | - method: 'GET' 177 | - expected_status: [400] 178 | 179 | - test: 180 | - name: 'Enterprise customer course enrollments endpoint returns HTTP 200' 181 | - url: '/enterprise/v1/enterprise-customer/0123456789abcdefg/course-enrollments' 182 | - method: 'POST' 183 | - headers: {'Authorization': 'aeiou', 'Content-Type': 'application/json'} 184 | - body: > 185 | [{ 186 | "course_run_id": "course-v1:edX+DemoX+Demo_Course", 187 | "course_mode": "audit", 188 | "user_email": "edx@example.com", 189 | "email_students": true 190 | }] 191 | - expected_status: [200] 192 | 193 | - test: 194 | - name: 'Enterprise customer course enrollments endpoint v2 returns HTTP 200' 195 | - url: '/enterprise/v2/enterprise-customer/0123456789abcdefg/course-enrollments' 196 | - method: 'POST' 197 | - headers: {'Authorization': 'aeiou', 'Content-Type': 'application/json'} 198 | - body: > 199 | [{ 200 | "course_run_id": "course-v1:edX+DemoX+Demo_Course", 201 | "course_mode": "audit", 202 | "user_email": "edx@example.com", 203 | "email_students": true 204 | }] 205 | - expected_status: [200] 206 | 207 | - test: 208 | - name: 'Enterprise customer course enrollments endpoint rejected without authorization' 209 | - url: '/enterprise/v1/enterprise-customer/0123456789abcdefg/course-enrollments' 210 | - method: 'POST' 211 | - headers: {'Content-Type': 'application/json'} 212 | - body: > 213 | [{ 214 | "course_run_id": "course-v1:edX+DemoX+Demo_Course", 215 | "course_mode": "audit", 216 | "user_email": "edx@example.com", 217 | "email_students": true 218 | }] 219 | - expected_status: [400] 220 | 221 | - test: 222 | - name: 'Enterprise customer course enrollments endpoint v2 rejected without authorization' 223 | - url: '/enterprise/v2/enterprise-customer/0123456789abcdefg/course-enrollments' 224 | - method: 'POST' 225 | - headers: {'Content-Type': 'application/json'} 226 | - body: > 227 | [{ 228 | "course_run_id": "course-v1:edX+DemoX+Demo_Course", 229 | "course_mode": "audit", 230 | "user_email": "edx@example.com", 231 | "email_students": true 232 | }] 233 | - expected_status: [400] 234 | 235 | - test: 236 | - name: 'Enterprise learner summary v3 endpoint returns HTTP 200' 237 | - url: '/enterprise/v3/enterprise-customer/9101d3de36156cba/learner-summary' 238 | - method: 'GET' 239 | - headers: {'Authorization': 'aeiou', 'Content-Type': 'application/json'} 240 | - expected_status: [200] 241 | 242 | - test: 243 | - name: 'Enterprise learner summary v3 endpoint rejected without authorization' 244 | - url: '/enterprise/v3/enterprise-customer/9101d3de36156cba/learner-summary' 245 | - method: 'GET' 246 | - headers: {'Content-Type': 'application/json'} 247 | - expected_status: [400] 248 | 249 | - test: 250 | - name: 'License assign endpoint returns HTTP 200' 251 | - url: '/enterprise/v1/subscriptions/9101d3de36156cba/licenses/assign' 252 | - method: 'POST' 253 | - headers: {'Authorization': 'aeiou', 'Content-Type': 'application/json'} 254 | - body: > 255 | [ 256 | { 257 | "user_emails": ["edx@example.com", "abc@example.com"], 258 | "user_sfids": ["efghijk", "abcdefg"], 259 | "greeting": "hello", 260 | "closing": "bye", 261 | "notify_users": true 262 | } 263 | ] 264 | - expected_status: [200] 265 | 266 | - test: 267 | - name: 'License assign endpoint rejected without authorization HTTP 400' 268 | - url: '/enterprise/v1/subscriptions/9101d3de36156cba/licenses/assign' 269 | - method: 'POST' 270 | - headers: {'Content-Type': 'application/json'} 271 | - body: > 272 | [ 273 | { 274 | "user_emails": ["edx@example.com", "abc@example.com"], 275 | "user_sfids": ["efghijk", "abcdefg"], 276 | "greeting": "hello", 277 | "closing": "bye", 278 | "notify_users": true 279 | } 280 | ] 281 | - expected_status: [400] 282 | 283 | - test: 284 | - name: 'Subscription Summary endpoint returns HTTP 200' 285 | - url: '/enterprise/v1/subscriptions/' 286 | - method: 'GET' 287 | - headers: {'Authorization': 'aeiou'} 288 | - expected_status: [200] 289 | 290 | - test: 291 | - name: 'Subscription Summary endpoint rejected without authorization HTTP 400' 292 | - url: '/enterprise/v1/subscriptions/' 293 | - method: 'GET' 294 | - expected_status: [400] 295 | 296 | - test: 297 | - name: 'License revokes endpoint returns HTTP 200' 298 | - url: '/enterprise/v1/subscriptions/9101d3de36156cba/licenses/bulk-revoke/' 299 | - method: 'POST' 300 | - headers: {'Authorization': 'aeiou', 'Content-Type': 'application/json'} 301 | - body: > 302 | [ 303 | { 304 | "user_emails": ["edx@example.com", "abc@example.com"] 305 | } 306 | ] 307 | - expected_status: [200] 308 | 309 | - test: 310 | - name: 'License revokes endpoint rejected without authorization HTTP 400' 311 | - url: '/enterprise/v1/subscriptions/9101d3de36156cba/licenses/bulk-revoke/' 312 | - method: 'POST' 313 | - headers: {'Content-Type': 'application/json'} 314 | - body: > 315 | [ 316 | { 317 | "user_emails": ["edx@example.com", "abc@example.com"] 318 | } 319 | ] 320 | - expected_status: [400] 321 | 322 | - test: 323 | - name: 'Bulk learner enrollment in given list of courses endpoint returns HTTP 200' 324 | - url: '/enterprise/v1/bulk-license-enrollment?enterprise_customer_uuid=234555' 325 | - method: 'POST' 326 | - headers: {'Authorization': 'aeiou', 'Content-Type': 'application/json'} 327 | - body: > 328 | [ 329 | { 330 | "emails": ["edx@example.com"], 331 | "course_run_keys": ["testX"], 332 | "notify": true 333 | } 334 | ] 335 | - expected_status: [200] 336 | 337 | - test: 338 | - name: 'Bulk learner enrollment in given list of courses endpoint returns HTTP 400 without enterprise_customer_uuid' 339 | - url: '/enterprise/v1/bulk-license-enrollment' 340 | - method: 'POST' 341 | - headers: {'Authorization': 'aeiou', 'Content-Type': 'application/json'} 342 | - body: > 343 | [ 344 | { 345 | "emails": ["edx@example.com"], 346 | "course_run_keys": ["testX"], 347 | "notify": true 348 | } 349 | ] 350 | - expected_status: [400] 351 | 352 | - test: 353 | - name: 'Bulk learner enrollment in given list of courses endpoint rejected without authorization HTTP 400' 354 | - url: '/enterprise/v1/bulk-license-enrollment' 355 | - method: 'POST' 356 | - headers: {'Content-Type': 'application/json'} 357 | - body: > 358 | [ 359 | { 360 | "emails": ["edx@example.com"], 361 | "course_run_keys": ["testX"], 362 | "notify": true 363 | } 364 | ] 365 | - expected_status: [400] 366 | -------------------------------------------------------------------------------- /tests/test_enterprise_access.yaml: -------------------------------------------------------------------------------- 1 | --- 2 | - config: 3 | - testset: 'Enterprise Access API' 4 | 5 | - test: 6 | - name: 'Policy Allocation endpoint returns HTTP 200' 7 | - url: '/enterprise/v1/policy-allocation/9101d3de36156cba/allocate' 8 | - method: 'POST' 9 | - headers: { 'Authorization': 'aeiou', 'Content-Type': 'application/json' } 10 | - body: > 11 | [ 12 | { 13 | "learner_emails": ["abc@example.com"], 14 | "content_key": "edx+101", 15 | "content_price_cents": 4500 16 | } 17 | ] 18 | - expected_status: [200] 19 | 20 | - test: 21 | - name: 'Policy Allocation endpoint rejected without Authorization' 22 | - url: '/enterprise/v1/policy-allocation/9101d3de36156cba/allocate' 23 | - method: 'POST' 24 | - expected_status: [400] 25 | 26 | - test: 27 | - name: 'Assignment configuration list endpoint returns HTTP 200' 28 | - url: '/enterprise/v1/assignment-configurations/9101d3de36156cba/admin/assignments/' 29 | - method: 'GET' 30 | - headers: { 'Authorization': 'aeiou', 'Content-Type': 'application/json' } 31 | - expected_status: [200] 32 | 33 | - test: 34 | - name: 'Assignment configuration list endpoint returns HTTP 200 with query params' 35 | - url: '/enterprise/v1/assignment-configurations/9101d3de36156cba/admin/assignments/?learner_state=notifying&state=allocated&state__in=allocated&state__in=accepted' 36 | - method: 'GET' 37 | - headers: { 'Authorization': 'aeiou', 'Content-Type': 'application/json' } 38 | - expected_status: [200] 39 | 40 | - test: 41 | - name: 'Assignment configuration list request rejected without authorization' 42 | - url: '/enterprise/v1/assignment-configurations/0123456789abcdefg/admin/assignments/' 43 | - method: 'GET' 44 | - expected_status: [400] 45 | 46 | - test: 47 | - name: 'Assignment configuration cancel endpoint returns HTTP 200' 48 | - url: '/enterprise/v1/assignment-configurations/9101d3de36156cba/admin/assignments/cancel/' 49 | - method: 'POST' 50 | - headers: { 'Authorization': 'aeiou', 'Content-Type': 'application/json' } 51 | - body: > 52 | [ 53 | { 54 | "assignment_uuids": ["01234567-89ab-cdef-0123-456789abcdef", "abcdef01-2345-6789-abcd-ef0123456789"] 55 | } 56 | ] 57 | - expected_status: [200] 58 | 59 | - test: 60 | - name: 'POST rejected without authorization' 61 | - url: '/enterprise/v1/assignment-configurations/0123456789abcdefg/admin/assignments/cancel/' 62 | - method: 'POST' 63 | - expected_status: [400] 64 | 65 | - test: 66 | - name: 'Assignment configuration remind endpoint returns HTTP 200' 67 | - url: '/enterprise/v1/assignment-configurations/9101d3de36156cba/admin/assignments/remind/' 68 | - method: 'POST' 69 | - headers: { 'Authorization': 'aeiou', 'Content-Type': 'application/json' } 70 | - body: > 71 | [ 72 | { 73 | "assignment_uuids": ["01234567-89ab-cdef-0123-456789abcdef", "abcdef01-2345-6789-abcd-ef0123456789"] 74 | } 75 | ] 76 | - expected_status: [200] 77 | 78 | - test: 79 | - name: 'POST rejected without authorization' 80 | - url: '/enterprise/v1/assignment-configurations/0123456789abcdefg/admin/assignments/remind/' 81 | - method: 'POST' 82 | - expected_status: [400] 83 | 84 | - test: 85 | - name: 'Subsidy Access Policy list endpoint returns HTTP 200' 86 | - url: '/enterprise/v1/subsidy-access-policies/?active=true&enterprise_customer_uuid=9101d3de36156cba&page=1&page_size=10&ploicy_type=content' 87 | - method: 'GET' 88 | - headers: { 'Authorization': 'aeiou', 'Content-Type': 'application/json' } 89 | - expected_status: [200] 90 | 91 | - test: 92 | - name: 'Subsidy Access Policy list endpoint rejected without authorization' 93 | - url: '/enterprise/v1/subsidy-access-policies/' 94 | - method: 'GET' 95 | - expected_status: [400] 96 | 97 | - test: 98 | - name: 'Subsidy Access Policy list endpoint returns HTTP 400 when required query param is missing' 99 | - url: '/enterprise/v1/subsidy-access-policies/' 100 | - method: 'GET' 101 | - headers: { 'Authorization': 'aeiou', 'Content-Type': 'application/json' } 102 | - expected_status: [400] 103 | -------------------------------------------------------------------------------- /tests/test_heartbeat.yaml: -------------------------------------------------------------------------------- 1 | --- 2 | - config: 3 | - testset: 'Heartbeat API' 4 | 5 | - test: 6 | - name: 'Endpoint returns HTTP 200 with version and id information' 7 | - url: '/heartbeat' 8 | - method: 'GET' 9 | - expected_status: [200] 10 | - validators: 11 | - compare: {jsonpath_mini: 'version', comparator: 'eq', expected: 'version'} 12 | - compare: {jsonpath_mini: 'id', comparator: 'eq', expected: 'id'} 13 | -------------------------------------------------------------------------------- /tests/test_index.yaml: -------------------------------------------------------------------------------- 1 | --- 2 | - config: 3 | - testset: 'Index API' 4 | 5 | - test: 6 | - name: 'Endpoint is defined and does not return an error. TODO: verify 302.' 7 | - url: '/heartbeat' 8 | - method: 'GET' 9 | -------------------------------------------------------------------------------- /tests/test_oauth.yaml: -------------------------------------------------------------------------------- 1 | --- 2 | - config: 3 | - testset: 'Oauth API' 4 | 5 | - test: 6 | - name: 'The GET method is not defined for this endpoint' 7 | - url: '/oauth2/v1/access_token' 8 | - method: 'GET' 9 | - expected_status: [405] 10 | 11 | - test: 12 | - name: 'POST request with only grant_type parameter returns a 400 code' 13 | - url: '/oauth2/v1/access_token' 14 | - method: 'POST' 15 | - headers: {'Content-Type': 'application/x-www-form-urlencoded'} 16 | - body: 'grant_type=foo' 17 | - expected_status: [400] 18 | 19 | - test: 20 | - name: 'POST request with only client_id parameter returns a 400 code' 21 | - url: '/oauth2/v1/access_token' 22 | - method: 'POST' 23 | - headers: {'Content-Type': 'application/x-www-form-urlencoded'} 24 | - body: 'client_id=foo' 25 | - expected_status: [400] 26 | 27 | - test: 28 | - name: 'POST request with required parameters succeeds' 29 | - url: '/oauth2/v1/access_token' 30 | - method: 'POST' 31 | - headers: {'Content-Type': 'application/x-www-form-urlencoded'} 32 | - body: 'grant_type=foo&client_id=bar' 33 | - expected_status: [200] 34 | - validators: 35 | - compare: {jsonpath_mini: 'access_token', comparator: 'eq', expected: 'access_token'} 36 | - compare: {jsonpath_mini: 'refresh_token', comparator: 'eq', expected: 'refresh_token'} 37 | - compare: {jsonpath_mini: 'scope', comparator: 'eq', expected: 'scope'} 38 | - compare: {jsonpath_mini: 'token_type', comparator: 'eq', expected: 'token_type'} 39 | - compare: {jsonpath_mini: 'expires_in', comparator: 'eq', expected: 0} 40 | --------------------------------------------------------------------------------