Skip to content

Commit

Permalink
add the --tail mode
Browse files Browse the repository at this point in the history
add --start and --end for more control
bump to 0.0.3
  • Loading branch information
bitonio committed May 26, 2021
1 parent 71d3da4 commit b72533b
Show file tree
Hide file tree
Showing 3 changed files with 68 additions and 23 deletions.
12 changes: 12 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,19 @@ Output is using JSON formatting, you'll find all the details about each attribut

## Command examples

Inline general help
```
% akamai mfa --help
```

Inline help for auth event
```
% akamai mfa event auth --help
```

Try to pull MFA events with the following examples.
When ``--start`` is omitted, start is set to 5 minutes ago.
When ``--end`` is omitted, end takes now minutes 30 seconds.

For Authentication events:

Expand Down
77 changes: 55 additions & 22 deletions bin/akamai-mfa
Original file line number Diff line number Diff line change
Expand Up @@ -39,12 +39,21 @@ import os
import json


__VERSION__ = "0.0.2"
__VERSION__ = "0.0.3"
LOG_FMT = '%(asctime)s [%(levelname)s] %(threadName)s %(message)s'
MOST_RECENT_PADDING = 30

log_file = None
mfa_api_url = "https://mfa.akamai.com"
mfa_api_ver = "v1"
tail_pull_interval = 60 # Default is 60
page_size = 10 # default is 1000


class MFAConfig():
"""
Manage CLI MFA input parameters
"""

CONFIG_KEYS = [
'mfa_integration_id',
Expand All @@ -65,6 +74,14 @@ class MFAConfig():
cmdparser = subparsers.add_parser('version', help="Display CLI-MFA version")
eventparser = subparsers.add_parser('event', help="Dump MFA events")
eventparser.add_argument("event_type", choices=['policy', 'auth'], default='policy', help="Event type")
eventparser.add_argument("--start", "-s", default=None, type=int, help="Scan for events after this epoch")
eventparser.add_argument("--end", "-e", default=None, type=int, help="Scan for events before this epoch")
eventparser.add_argument("--tail", "-f", default=False, action="store_true",
help="""Do not stop when most recent log is reached, rather
wait for additional data to be appended to the input.""")
eventparser.add_argument("--noreceipt", default=False, action="store_true",
help="Discard the receipt attribute to save log space")

parser.add_argument("--edgerc", type=argparse.FileType('r'), default=os.path.expanduser("~/.edgerc"),
help='Location of the credentials file (default is %s)' % os.path.expanduser("~/.edgerc"))

Expand Down Expand Up @@ -152,35 +169,51 @@ if __name__ == "__main__":
print(__VERSION__)
sys.exit(0)


mfa_api_url = "https://mfa.akamai.com"
mfa_api_ver = "v1"

session = requests.Session()
session.headers.update({'User-Agent': f'cli-mfa/{__VERSION__}'})
session.auth = AkamaiMFAAuth(config)

page_size = 10
scan_end = datetime.datetime.utcnow()
scan_start = scan_end - datetime.timedelta(days=2)

if config.event_type == 'auth':
api_report_type = 'auths'
elif config.event_type == 'policy':
api_report_type = 'policies'

api_url = f'{mfa_api_url}/api/{mfa_api_ver}/control/reports/{api_report_type}'
page = 1
page_count = None
while page_count is None or page <= page_count:
params = {
'after': scan_start.isoformat(),
'before': scan_end.isoformat(),
'page_size': page_size,
'page': page
}
r = session.get(api_url, params=params)
page += 1
page_count = r.json().get('result', {}).get('total_page_count')
for mfa_event in r.json().get('result', {}).get('page'):
print(json.dumps(mfa_event))
scan_end = datetime.datetime.utcnow() - datetime.timedelta(seconds=MOST_RECENT_PADDING)
scan_start = scan_end - datetime.timedelta(minutes=5)
if config.end:
scan_end = datetime.datetime.utcfromtimestamp(config.end)
if config.start:
scan_start = datetime.datetime.utcfromtimestamp(config.start)


while True:
loop_start = time.time()
page = 1
page_count = None
while page_count is None or page <= page_count:
params = {
'after': scan_start.isoformat(),
'before': scan_end.isoformat(),
'page_size': page_size,
'page': page
}
r = session.get(api_url, params=params)
page += 1
page_count = r.json().get('result', {}).get('total_page_count')
for mfa_event in r.json().get('result', {}).get('page'):
if config.noreceipt:
mfa_event.pop('receipt')
print(json.dumps(mfa_event))
sys.stdout.flush()

if config.tail:
wait = tail_pull_interval - (time.time() - loop_start)
logging.debug("Wait %s sec..." % wait)
time.sleep(wait)
scan_start = scan_end # next iteration we stich, start is the previous end
scan_end = datetime.datetime.utcnow() - datetime.timedelta(seconds=MOST_RECENT_PADDING)

else:
break
2 changes: 1 addition & 1 deletion cli.json
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
"commands": [
{
"name": "mfa",
"version": "0.0.2",
"version": "0.0.3",
"description": "Akamai CLI for MFA"
}
]
Expand Down

0 comments on commit b72533b

Please sign in to comment.