r/PowerShell • • Oct 06 '19

PSApi: ultra-fast way to create a webservice

I've published PSApi to the Powershell Gallery today. It is intended as a super-lightweight way to create a webservice. Quickest way to explain is probably with a screenshot.

The design goals were:

  • To be minimalist. If you can write a function you can create a webservice from it. Defaults should do most of the heavy lifting.

  • To be efficient. The "server" is multi-threaded so should be able to handle quite a lot of requests.

  • To work cross platform.

  • To be relatively secure*. Commands are walked for dependencies and custom runspaces are built from them.

(Security is hard. I encourage anyone to see if they can exploit this somehow. I would love to hear about it so it can be fixed.)

The module is on the gallery, so you can install it with

Install-Module PSApi -Scope 'CurrentUser'

Source is available on GitHub. This is version 0.0.9. Expect some bugs, and please do let me know, if you run into any. Contributions are welcome, as long as they fit within the design goals outlined above.

The use cases I envisioned for this was creating monitoring points, the ability to create simple mock-up services, and generally being yet another tool in the box used to "glue" PowerShell together with other things. It can do a whole lot more than that, though.

Here is a simple function for getting user pictures from your AD, provided you've populated the thumbnail property (expanded version here that also does high quality rescaling). It uses ADSI, because Core. Publish-Command UserPhoto and you have an image service.

function UserPhoto ($user) {
    $user_data = ([adsisearcher]"(&(objectClass=user)(sAMAccountName=$user))").FindAll()
    $stream = [System.Io.MemoryStream]::new($user_data.Properties["thumbnailphoto"][0])
    $img = [System.Drawing.Image]::FromStream($stream)
    $img
}

Lots more information can be found on GitHub, regarding usage, how to run as non-administrator, how to post funky parameters, etc. But generally: just Publish-Command <function> and you're done! :)

Enjoy!

Edit: *Just a clarification. Security in this context doesn't mean authentication, this module provides none. Focus on security here is in trying to protect the integrity of the machine serving the commands.

120 Upvotes

14 comments sorted by

9

u/joerod Oct 06 '19

What authentication methods does this support?

13

u/NotNotWrongUsually Oct 06 '19

None. I wanted it to work cross platform, and these are the supported authentication schemes for HttpListener. I suppose Basic could be supported quite easily but I feel I'd be doing the world a disservice.

I'd rather have people only publish stuff that needs no authentication, than have to authenticate with what is essentially clear-text credentials.

9

u/Emiroda Oct 06 '19

That's a good point, and it sort of limits what this module "should" be used for in production. Not a direct jab at your project, it's actually a fantastic idea. And so much more simple than the other PowerShell web projects I've seen.

Maybe you could study how others implement stuff like cert-authentication or API keys? (sorry for giving you extra work already instead of celebrating the first release 🤭). I realise this requires using external dependencies and probably bloats the project by a bit, but on the other hand if you choose to use it without authentication, you wouldn't need to load the code for it.

3

u/NotNotWrongUsually Oct 06 '19

Haha, all good. My line of thinking is that if you are a shop that is prepared to work with certs and API keys you have other (and better) ways to secure this (API gateways, firewalls, traffic managers, reverse proxies, etc.)

I did take a look at oAuth while developing, and quickly thought "yep, that is definitely for a v2.0.0". That stuff looks daunting to implement!

4

u/gazataeon Oct 06 '19

Have you tried Pode? https://github.com/Badgerati/Pode
It's got cross platform and looks to be a good fit for what you're after!

6

u/NotNotWrongUsually Oct 06 '19

Unfortunately it seems Pode only has built-in authentication options for Windows as well. Same deal for Polaris. Was hoping to find something in their codebases for inspiration.

To be fair Pode, Polaris, and other similar micro-frameworks were what I was trying to get away from with this. Don't get me wrong, they do brilliant stuff, but the scope is different. I wanted something where you didn't have to worry about route management, and a lot of other scaffolding to just serve a humble function. I suppose I could call this a ... nano-framework?

"Nano-frameworks! When micro-frameworks are just too much of a hassle!"

5

u/Badgerati Oct 06 '19

Yo!

Like the idea of a nano-framework, haha!

On the front of authentication, Polaris definitely has the Window pitfall. As for Pode, it's authentication is completely isolated from HttpListener - using middleware instead; so basic, form, or any other custom authentication all work xplat (.NET allowing). I'll admit that AD does only work on Windows currently, but then that was .NET Core not supporting it - though you could use the Novell framework in Pode, where as in Polaris you can't and are restricted to just the HttpListener methods.

I agree that full on route management is a hassle though, especially if you just want something small and not a full blown REST API or website!

4

u/Sekers Oct 06 '19

This is neat. Any issues with Powershell continuously running such as random crashes or increasing memory consumption?

4

u/NotNotWrongUsually Oct 06 '19 edited Oct 07 '19

Good question! I did some testing during development, but that was many edits ago, so decided to repeat.

The test:

  • Publish-Command Get-Process from pwsh

  • Open two regular Windows PowerShell windows and have them hammer away Invoke-WebRequest as fast as possible.

At start pwsh was listing as using 56.9 MB of memory.

After about ten minutes and 7,556 requests, the usage was 92.9 MB when i stopped the requests. So there is some leak somewhere (after 21,000 requests you'd have leaked 100MB).

I'll see if I can track it down, but I'm not sure if it something I can release, or if it is something in the shell building up.

As for leaving the shell open with a running process for a long time, I've done that before with no problem.

Edit: fixed and uploaded to the gallery in v0.0.10

0

u/[deleted] Oct 06 '19

[deleted]

4

u/NotNotWrongUsually Oct 06 '19 edited Oct 06 '19

Still had the window open, so yes, I can. Forced GC reduced memory consumption, but only to 85.7 MB.

Still, for the purposes I had intended for this, I suppose it could run for years without having to be restarted as it is. Pretty sure someone will restart the shell or machine for other reasons before the memory issue become a problem.

Of course, other people might have other purposes, so I am going to track down the leak if I can. Any and all help in that regard is welcome. I just went over the code, but am not seeing any red flags.

3

u/NotNotWrongUsually Oct 07 '19

Happy to say I've found the solution for this one. Memory usage is now rock solid!

Unfortunately I'm currently behind a million proxies and firewalls so can't push code to GitHub. It'll be added when I'm home ;)

5

u/realslacker Oct 06 '19

This is really cool, can't wait to check it out!

0

u/[deleted] Oct 07 '19

[deleted]

3

u/NotNotWrongUsually Oct 07 '19 edited Oct 07 '19

Strange. If you use another variable name than $Name everything seems to work just fine. There must be some bug in the dependency walker which I need to sort out. For now, you can workaround your problem by not using $Name. This works fine:

function GetSvcJson {
    param(
        [Parameter(Mandatory=$true)]
        $svc
    )
    Get-Service -Name $svc | ConvertTo-Json
}

Yes. That is odd. The dependency walker can be a bit special at times.

Curious side effect of your code that I should really get around to documenting: when you set a parameter to mandatory, you will actually get prompted to supply a value for it in the shell, if you don't supply it in the browser.

This is obviously not much good to a remote user, but there is no setting to prevent this behavior in Powershell. I'm torn on whether I should manipulate the function when putting it in the runspace or not. It is possible to convert the parameter to a non-mandatory parameter that does a throw if it isn't filled in. This prevents the behaviour.

Edit: In this particular case you can remove the problem by just removing the mandatory on the parameter btw. The service will throw an error 500 with an explanation if it isn't included anyways, which is much desirable compared to the behaviour described above.

Edit2: I've located the bug. The dependency walker was looking in its own scope. There is a variable called $Name there already. It confuses yours with its own. A cascade of fail follows. I have some code sitting on my own machine to sort it out, but it needs to be more thoroughly tested before I put it on GitHub. That is going to have to be tomorrow.

2

u/NotNotWrongUsually Oct 08 '19

This is now fixed, and Update-Module should get you v.0.0.11 without the bug. It was specifically the variable name $Name that had this problem, and no other.

I officially extend my apology to any software developer at whom I have cursed 'How was this not found in testing!'.