Skip to content

Commit

Permalink
flare.py: add missing typing + splunk useragent + renamed serverKey t…
Browse files Browse the repository at this point in the history
…o apiKey
  • Loading branch information
aviau authored and Marc-Antoine Hinse committed Oct 31, 2024
1 parent cfd914a commit 3ebd76b
Show file tree
Hide file tree
Showing 6 changed files with 68 additions and 37 deletions.
24 changes: 12 additions & 12 deletions packages/configuration-screen/src/ConfigurationScreen.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import React, { useEffect, useState } from 'react';
import Button from '@splunk/react-ui/Button';
import {
retrieveServerKey,
retrieveApiKey,
retrieveTenantId,
retrieveUserTenants,
saveConfiguration,
Expand All @@ -10,16 +10,16 @@ import { StyledContainer, StyledError } from './ConfigurationScreenStyles';
import { Tenant } from './models/flare';

const ConfigurationScreen = () => {
const [serverKey, setServerKey] = useState('');
const [apiKey, setApiKey] = useState('');
const [tenantId, setTenantId] = useState(-1);
const [errorMessage, setErrorMessage] = useState('');
const [tenants, setUserTenants] = useState<Tenant[]>([]);
const [isLoading, setIsLoading] = useState(false);

function handleSubmitServerKey() {
function handleSubmitApiKey() {
setIsLoading(true);
retrieveUserTenants(
serverKey,
apiKey,
(userTenants) => {
if (tenantId === -1 && userTenants.length > 0) {
setTenantId(userTenants[0].id);
Expand All @@ -37,13 +37,13 @@ const ConfigurationScreen = () => {

async function handleSubmitTenant() {
setIsLoading(true);
await saveConfiguration(serverKey, tenantId);
await saveConfiguration(apiKey, tenantId);
}

useEffect(() => {
setIsLoading(true);
retrieveServerKey().then((key) => {
setServerKey(key);
retrieveApiKey().then((key) => {
setApiKey(key);
retrieveTenantId().then((id) => {
setTenantId(id);
setIsLoading(false);
Expand All @@ -54,7 +54,7 @@ const ConfigurationScreen = () => {
if (isLoading) {
return <div>Loading...</div>;
}
if (tenants.length === 0 || serverKey === '') {
if (tenants.length === 0 || apiKey === '') {
return (
<StyledContainer>
<h2>Enter your API Key</h2>
Expand All @@ -64,13 +64,13 @@ const ConfigurationScreen = () => {
<br />
<input
type="password"
name="serverKey"
value={serverKey}
onChange={(e) => setServerKey(e.target.value)}
name="apiKey"
value={apiKey}
onChange={(e) => setApiKey(e.target.value)}
/>
<br />
<br />
<Button onClick={() => handleSubmitServerKey()}>Next Step</Button>
<Button onClick={() => handleSubmitApiKey()}>Next Step</Button>
</StyledContainer>
);
}
Expand Down
18 changes: 9 additions & 9 deletions packages/configuration-screen/src/setupConfiguration.ts
Original file line number Diff line number Diff line change
Expand Up @@ -54,12 +54,12 @@ function createService(applicationNamespace: SplunkApplicationNamespace): Splunk
}

function retrieveUserTenants(
serverKey: string,
apiKey: string,
successCallback: (userTenants: Array<Tenant>) => void,
errorCallback: (errorMessage: string) => void
): void {
const service = createService(applicationNameSpace);
const data = { serverKey };
const data = { apiKey };
service.post('/services/retrieve_user_tenants', data, (err, response) => {
if (err) {
errorCallback(err.data);
Expand Down Expand Up @@ -97,12 +97,12 @@ async function savePassword(
});
}

async function saveConfiguration(serverKey: string, tenantId: number) {
async function saveConfiguration(apiKey: string, tenantId: number) {
const service = createService(applicationNameSpace);

const storagePasswords = await promisify(service.storagePasswords().fetch)();
await savePassword(storagePasswords, 'serverkey', serverKey);
await savePassword(storagePasswords, 'tenantid', `${tenantId}`);
await savePassword(storagePasswords, 'api_key', apiKey);
await savePassword(storagePasswords, 'tenant_id', `${tenantId}`);

await completeSetup(service);
await reloadApp(service);
Expand All @@ -123,12 +123,12 @@ async function retrievePassword(passwordKey: string): Promise<string> {
return '';
}

async function retrieveServerKey(): Promise<string> {
return retrievePassword('serverkey');
async function retrieveApiKey(): Promise<string> {
return retrievePassword('api_key');
}

async function retrieveTenantId(): Promise<number> {
return retrievePassword('tenantid').then((tenantId) => {
return retrievePassword('tenant_id').then((tenantId) => {
if (tenantId !== '') {
return parseInt(tenantId, 10);
}
Expand All @@ -137,4 +137,4 @@ async function retrieveTenantId(): Promise<number> {
});
}

export { saveConfiguration, retrieveUserTenants, retrieveServerKey, retrieveTenantId };
export { saveConfiguration, retrieveUserTenants, retrieveApiKey, retrieveTenantId };
File renamed without changes.
59 changes: 45 additions & 14 deletions packages/flare/python/flare.py
Original file line number Diff line number Diff line change
@@ -1,37 +1,68 @@
from http.client import HTTPMessage
from typing import Optional
from typing import Any
import typing as t
import sys

from vendor.requests.auth import AuthBase

from urllib.error import HTTPError
from vendor.flareio import FlareApiClient
import vendor.splunklib.client as client

APP_NAME = "flare"


def ensure_str(value: t.Union[str, bytes]) -> str:
if isinstance(value, bytes):
return value.decode("utf8")
return value


def get_flare_api_client(
*,
api_key: str,
tenant_id: t.Union[int, None],
) -> FlareApiClient:
api_client = FlareApiClient(
api_key=api_key,
tenant_id=tenant_id,
)
current_user_agent: str = ensure_str(
api_client._session.headers.get("User-Agent") or ""
)
api_client._session.headers["User-Agent"] = (
f"{current_user_agent} flare-splunk".strip()
)
return api_client


class FlareAPI(AuthBase):
def __init__(self, *, app):
def __init__(self, *, app: client.Application) -> None:
# Should be able to use app.service.storage_passwords.get(),
# but I can't seem to get that to work. list() works.
server_key: Optional[str] = None
tenant_id: Optional[str] = None
api_key: t.Optional[str] = None
tenant_id: t.Optional[int] = None
for item in app.service.storage_passwords.list():
if item.content.username == "serverkey":
server_key = item.clear_password
if item.content.username == "api_key":
api_key = item.clear_password

if item.content.username == "tenantid":
tenant_id = item.clear_password
if item.content.username == "tenant_id":
tenant_id = (
int(item.clear_password)
if item.clear_password is not None
else None
)

if not api_key:
raise Exception("API key not found")

self.flare_endpoints = app.service.confs["flare"]["endpoints"]
self.api_key = server_key
self.tenant_id = tenant_id
self.flare_client = FlareApiClient(
api_key=self.api_key, tenant_id=self.tenant_id

self.flare_client = get_flare_api_client(
api_key=api_key,
tenant_id=tenant_id,
)

def retrieve_feed(self, *, from_: Optional[str] = None) -> dict[str, Any]:
def retrieve_feed(self, *, from_: t.Optional[str] = None) -> dict[str, t.Any]:
url = self.flare_endpoints["me_feed_endpoint"]
response = self.flare_client.post(
url=url,
Expand Down
2 changes: 1 addition & 1 deletion packages/flare/python/flare_external_requests.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ class FlareUserTenants(splunk.rest.BaseRestHandler):
def handle_POST(self):
payload = self.request["payload"]
params = parseParams(payload)
self.flare_client = FlareApiClient(api_key=params["serverKey"])
self.flare_client = FlareApiClient(api_key=params["apiKey"])
user_tenants_response = self.flare_client.get("firework/v2/me/tenants")
self.response.setHeader("Content-Type", "application/json")
self.response.write(json.dumps(user_tenants_response.json()))
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
[script://$SPLUNK_HOME/etc/apps/flare/bin/input.py]
[script://$SPLUNK_HOME/etc/apps/flare/bin/cron_job_ingest_events.py]
interval = * * * * *
python.version = python3
source = Flare
Expand Down

0 comments on commit 3ebd76b

Please sign in to comment.